Java Reference
In-Depth Information
The andThen() method returns a composed Function that applies this function to the argument, and then
applies the specified after function to the result. The compose() function returns a composed function that applies
the specified before function to the argument, and then applies this function to the result. The identify() method
returns a function that always returns its argument.
The following snippet of code demonstrates how to use default and static methods of the Function interface to
compose new functions:
// Create two functions
Function<Long, Long> square = x -> x * x;
Function<Long, Long> addOne = x -> x + 1;
// Compose functions from the two functions
Function<Long, Long> squareAddOne = square.andThen(addOne);
Function<Long, Long> addOneSquare = square.compose(addOne);
// Get an identity function
Function<Long, Long> identity = Function.<Long>identity();
// Test the functions
long num = 5L;
System.out.println("Number : " + num);
System.out.println("Square and then add one: " + squareAddOne.apply(num));
System.out.println("Add one and then square: " + addOneSquare.apply(num));
System.out.println("Identity: " + identity.apply(num));
Number: 5
Square and then add one: 26
Add one and then square: 36
Identity: 5
You are not limited to composing a function that consists of two functions that are executed in a specific order.
A function may be composed of as many functions as you want. You can chain lambda expressions to create a
composed function in one expression. Note that when you chain lambda expressions, you may need to provide
hints to the compiler to resolve the target type ambiguity that may arise. The following is an example of a composed
function by chaining three functions. A cast is provided to help the compiler. Without the cast, the compiler will not be
able to infer the target type.
// Square the input, add one to the result, and square the result
Function<Long, Long> chainedFunction = ((Function<Long, Long>)(x -> x * x))
.andThen(x -> x + 1)
.andThen(x -> x * x);
System.out.println(chainedFunction.apply(3L));
100
Search WWH ::




Custom Search