Creating composite functions in Java 8
In Java 8, we can use the
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
Function<Double, Double> doubleFunction = x -> 2 * x; Function<Double, Double> second = doubleFunction.compose(x -> -x);
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.
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.