Functional interface composition: andThen/compose, and/or/negate
Function.andThen/compose and Predicate.and/or/negate let you build complex behavior out of small
pieces without writing a new lambda each time -- and andThen vs compose differ only in order:
andThen runs the original function first, compose runs the argument first.
import java.util.function.*;
Function<Integer, Integer> times2 = x -> x * 2;
Function<Integer, Integer> plus3 = x -> x + 3;
Function<Integer, Integer> andThen = times2.andThen(plus3); // times2 FIRST, then plus3
Function<Integer, Integer> compose = times2.compose(plus3); // plus3 FIRST, then times2
System.out.println("andThen(5): (5*2)+3 = " + andThen.apply(5));
System.out.println("compose(5): (5+3)*2 = " + compose.apply(5));
Predicate<Integer> isPositive = x -> x > 0;
Predicate<Integer> isEven = x -> x % 2 == 0;
Predicate<Integer> positiveAndEven = isPositive.and(isEven);
Predicate<Integer> positiveOrEven = isPositive.or(isEven);
Predicate<Integer> notPositive = isPositive.negate();
for (int n : java.util.List.of(-4, -3, 2, 5)) {
System.out.printf(" %d: positiveAndEven=%b, positiveOrEven=%b, notPositive=%b%n",
n, positiveAndEven.test(n), positiveOrEven.test(n), notPositive.test(n));
}