Function:
- A functional interface in java.util.function.
- Represents a transformation: takes an input of type T and produces an output of type R.
Core Method:
R apply(T t)
Extra Methods in Function:
Function is more powerful than Consumer because it supports chaining both before and after.
1. andThen(Function after)
First applies the current function, then applies the after function on the result.
Function<String, Integer> lengthFinder = str -> str.length();
Function<Integer, Integer> square = n -> n * n;
Function<String, Integer> lengthSquared = lengthFinder.andThen(square);
System.out.println(lengthSquared.apply("Java")); // 16
2. compose(Function before)
First applies the before function, then applies the current function.
Function<Integer, Integer> square = n -> n * n;
Function<Integer, String> toString = n -> "Result: " + n;
Function<Integer, String> squareThenString = toString.compose(square);
System.out.println(squareThenString.apply(5)); // Result: 25
Example for Compose
import java.util.function.Function;
public class FunctionOrderDemo {
public static void main(String[] args) {
Function<Integer, Integer> add2 = n -> n + 2;
Function<Integer, Integer> 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
}
}
Why not just use andThen always?
-If you always want current → after, andThen is enough.
-But sometimes you need the other order (before → current).
Example:
-You want to preprocess input before applying your main function.
-That’s when compose is useful.
I think it is useful to everyone see u Soon....
Top comments (0)