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
Functional Composition
Functional Programming with Java - Composition
Functional composition refers to a technique where multiple functions are combined together to a single function. We can combine lambda expression together. Java provides inbuilt support using Predicate and Function classes. Following example shows how to combine two functions using predicate approach.
import java.util.function.Predicate; pubpc class FunctionTester { pubpc static void main(String[] args) { Predicate<String> hasName = text -> text.contains("name"); Predicate<String> hasPassword = text -> text.contains("password"); Predicate<String> hasBothNameAndPassword = hasName.and(hasPassword); String queryString = "name=test;password=test"; System.out.println(hasBothNameAndPassword.test(queryString)); } }
Output
true
Predicate provides and() and or() method to combine functions. Whereas Function provides compose and andThen methods to combine functions. Following example shows how to combine two functions using Function approach.
import java.util.function.Function; pubpc class FunctionTester { pubpc static void main(String[] args) { Function<Integer, Integer> multiply = t -> t *3; Function<Integer, Integer> add = t -> t + 3; Function<Integer, Integer> FirstMultiplyThenAdd = multiply.compose(add); Function<Integer, Integer> FirstAddThenMultiply = multiply.andThen(add); System.out.println(FirstMultiplyThenAdd.apply(3)); System.out.println(FirstAddThenMultiply.apply(3)); } }
Output
18 12Advertisements