Functional Programming - Composition
Predicate Approach to combine Functions
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.
FunctionTester.java
package com.tutorialspoint;
import java.util.function.Predicate;
public class FunctionTester {
public 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
Run the FunctionTester and verify the output.
true
Functional Approach to combine Functions
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.
FunctionTester.java
package com.tutorialspoint;
import java.util.function.Function;
public class FunctionTester {
public 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
Run the FunctionTester and verify the output.
18 12
Advertisements