Java › Functional Interfaces & Method References
How do the default methods andThen() and compose() on Function work, and what's the difference between them for chaining transformations?
IntermediateAnswer
andThen(after) creates a composed function that first applies the original function, then applies the 'after' function to that result (f.andThen(g) means g(f(x))); compose(before) instead creates a composed function that first applies the 'before' function, then applies the original (f.compose(g) means f(g(x))) -- the key distinction is the ORDER of application: andThen reads left-to-right matching the chain's declaration order, while compose reads right-to-left, and choosing the wrong one for your intended order produces a function that runs its steps in the opposite sequence from what you intended.
Function<Integer, Integer> addOne = x -> x + 1;
Function<Integer, Integer> multiplyByTwo = x -> x * 2;
Function<Integer, Integer> addThenMultiply = addOne.andThen(multiplyByTwo);
System.out.println(addThenMultiply.apply(3)); // (3+1)*2 = 8
Function<Integer, Integer> multiplyThenAdd = addOne.compose(multiplyByTwo);
System.out.println(multiplyThenAdd.apply(3)); // (3*2)+1 = 7 -- compose applies multiplyByTwo FIRSTReal-world example A data-transformation pipeline needing to first sanitize input then apply a business calculation chains sanitize.andThen(calculate) to express this order explicitly and readably, choosing andThen specifically because its left-to-right reading matches the intended sanitize-then-calculate sequence.