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
First Class Functions
Functional Programming - First Class Function
A function is called a first class function if it fulfills the following requirements.
It can be passed as a parameter to a function.
It can be returned from a function.
It can be assigned to a variable and then can be used later.
Java 8 supports functions as first class object using lambda expressions. A lambda expression is a function definition and can be assigned to a variable, can be passed as an argument and can be returned. See the example below −
@FunctionalInterface interface Calculator<X, Y> { pubpc X compute(X a, Y b); } pubpc class FunctionTester { pubpc static void main(String[] args) { //Assign a function to a variable Calculator<Integer, Integer> calculator = (a,b) -> a * b; //call a function using function variable System.out.println(calculator.compute(2, 3)); //Pass the function as a parameter printResult(calculator, 2, 3); //Get the function as a return result Calculator<Integer, Integer> calculator1 = getCalculator(); System.out.println(calculator1.compute(2, 3)); } //Function as a parameter static void printResult(Calculator<Integer, Integer> calculator, Integer a, Integer b){ System.out.println(calculator.compute(a, b)); } //Function as return value static Calculator<Integer, Integer> getCalculator(){ Calculator<Integer, Integer> calculator = (a,b) -> a * b; return calculator; } }
Output
6 6 6Advertisements