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 ...

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.