Mastery
Mastery/Java/D. Streams & functional interfaces
T2 · intermediate depth

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.

java
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));
java
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));
}

Interview angle

A quick, precise check: "what's the difference between f.andThen(g) and f.compose(g)?" Candidates who've only glanced at the functional interfaces often guess, rather than knowing confidently — a good sign of whether someone has actually built a validation pipeline or filter chain with these methods versus just writing individual lambdas.

In the industry

Predicate.and/or/negate are the standard way to compose filter conditions without duplicating stream .filter() calls or writing a nested boolean expression by hand — especially useful for building up a condition from named, independently-testable pieces (isActive.and(isPastDue)). Function.andThen/compose are common in validation and transformation pipelines where each step is a small, named function rather than one large lambda that's hard to unit test in isolation.