O'Reilly logo

Learning Java Functional Programming by Richard M Reese

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required