Video in progress

Strong Middle 🌊 Streams and lambdas

What's the difference between Function.andThen and compose? How do you combine Predicates?

f.andThen(g) means f first, then g: g(f(x)). f.compose(g) means g first, then f: f(g(x)). Predicates combine with and, or, negate, and since Java 11 Predicate.not(...) is handy for negating a method reference.

📖 Answer

Function<String, String> trim = String::trim;
Function<String, String> upper = String::toUpperCase;
Function<String, Integer> len = String::length;

trim.andThen(upper).apply("  salom ");   // "SALOM"
len.compose(trim).apply("  salom ");     // 5: trim first, then length

To remember: andThen is in reading order, compose is f ∘ g from math. In practice I almost only use andThen, because it reads naturally.

Predicates:

Predicate<User> active = User::active;
Predicate<User> adult = u -> u.age() >= 18;
Predicate<User> blocked = User::blocked;

users.stream().filter(active.and(adult).and(blocked.negate()));
users.stream().filter(Predicate.not(User::blocked));   // Java 11+
lines.stream().filter(Predicate.not(String::isBlank));

and and or short-circuit: if the first predicate decides the answer, the second isn't called. So put the cheap check first.

Where this is useful: when the rules are assembled from a list.

Predicate<Order> rule = filters.stream()
        .reduce(o -> true, Predicate::and);   // all filters joined with "and"

One trap: if you call andThen on a UnaryOperator<String>, the result is a Function<String, String>, not a UnaryOperator, so you can't pass it directly where a UnaryOperator is expected, like replaceAll.