Functional Programming with Java Tutorial
Selected Reading
- Discussion
- Resources
- Quick Guide
- Fixed Length Streams
- Infinite Streams
- Terminal methods
- Intermediate Methods
- Exception Handling
- Type Inference
- Pure Functions
- First Class Functions
- Returning a Function
- High Order Functions
- Collections
- Constructor References
- Method References
- Functional Interfaces
- Default Methods
- Lambda Expressions
- Reducing
- Currying
- Closure
- Optionals & Monads
- Parallelism
- Recursion
- Persistent Data Structure
- Eager vs Lazy Evaluation
- Functional Composition
- Functions
- Overview
- Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Closure
Functional Programming with Java - Closure
A closure is a function which is a combination of function along with its surrounding state. A closure function generally have access to outer function s scope. In the example given below, we have created a function getWeekDay(String[] days) which returns a function which can return the text equivalent of a weekday. Here getWeekDay() is a closure which is returning a function surrounding the calpng function s scope.
Following example shows how Closure works.
import java.util.function.Function; pubpc class FunctionTester { pubpc static void main(String[] args) { String[] weekDays = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; Function<Integer, String> getIndianWeekDay = getWeekDay(weekDays); System.out.println(getIndianWeekDay.apply(6)); } pubpc static Function<Integer, String> getWeekDay(String[] weekDays){ return index -> index >= 0 ? weekDays[index % 7] : null; } }
Output
SundayAdvertisements