Creating composite functions in Java 8
In Java 8, we can use the Function
interface's compose
method along with lambda expressions instead to achieve the same results with a lot less effort as shown next. The output will still be -10
:
Function<Double, Double> doubleFunction = x -> 2 * x; Function<Double, Double> second = doubleFunction.compose(x -> -x);
The Function
interface is found in the java.util.function
package. The source code for this interface is shown next. The default compose
method is passed a single function and returns a function encapsulating the passed function. The requireNonNull
method is used to support null values, and will be discussed in Chapter 6, Optional and Monads. The andThen
method will be discussed shortly.
Note
The compose
method uses a parameter named, before
, and the andThen
method uses a parameter named, after
. These names indicate the order that the functions will be evaluated on.
@FunctionalInterface public interface...