Part-4 Functional Interface(Function)
Source: Dev.to
Functional Interface: Function
A functional interface in java.util.function that represents a transformation: it takes an input of type T and produces an output of type R.
Core Method
R apply(T t);
Extra Methods
andThen(Function after)
Chains another function to be executed after the current one.
Function lengthFinder = str -> str.length();
Function square = n -> n * n;
Function lengthSquared = lengthFinder.andThen(square);
System.out.println(lengthSquared.apply("Java")); // 16
compose(Function before)
Applies another function before the current one.
Function square = n -> n * n;
Function toString = n -> "Result: " + n;
Function squareThenString = toString.compose(square);
System.out.println(squareThenString.apply(5)); // Result: 25
Example: Function Order Demo
import java.util.function.Function;
public class FunctionOrderDemo {
public static void main(String[] args) {
Function add2 = n -> n + 2;
Function multiply3 = n -> n * 3;
// andThen → current first, then after
System.out.println(add2.andThen(multiply3).apply(5));
// (5 + 2) * 3 = 21
// compose → before first, then current
System.out.println(add2.compose(multiply3).apply(5));
// (5 * 3) + 2 = 17
}
}
When to Use andThen vs. compose
andThenis sufficient when you want to apply the current function first and then another function (current → after).composeis useful when you need to preprocess the input before applying the main function (before → current).