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.


The ...

Get Learning Java Functional Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.