
- Functional Programming with Java Tutorial
- Home
- Overview
- Aspects
- Functions
- Functional Composition
- Eager vs Lazy Evaluation
- Persistent Data Structure
- Recursion
- Parallelism
- Optionals & Monads
- Closure
- Currying
- Reducing
- Java 8 Onwards
- Lambda Expressions
- Default Methods
- Functional Interfaces
- Method References
- Constructor References
- Collections
- Functional Programming
- High Order Functions
- Returning a Function
- First Class Functions
- Pure Functions
- Type Inference
- Exception Handling
in Lambda Expressions - Streams
- Intermediate Methods
- Terminal methods
- Infinite Streams
- Fixed Length Streams
- Useful Resources
- Quick Guide
- Resources
- Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Functional Programming - Returning a Function
As a High Order function can return a function but how to implement using Java 8. Java 8 has provided Function interface which can accept a lambda expression. A high order function can return a lamdba expression and thus this high order function can be used to create any number of functions. See the example below −
import java.util.function.Function; public class FunctionTester { public static void main(String[] args) { Function<Integer, Integer> addOne = adder(1); Function<Integer, Integer> addTwo = adder(2); Function<Integer, Integer> addThree = adder(3); //result = 4 + 1 = 5 Integer result = addOne.apply(4); System.out.println(result); //result = 4 + 2 = 6 result = addTwo.apply(4); System.out.println(result); //result = 4 + 3 = 7 result = addThree.apply(4); System.out.println(result); } //adder - High Order Function //returns a function as lambda expression static Function<Integer, Integer> adder(Integer x){ return y -> y + x; } }
Output
5 6 7
Advertisements