Function.andThen() vs Function.compose()
Fast recall
Quick revision
Core answer
f.andThen(g) applies f first and passes its result to g, so it represents g(f(x)). f.compose(g) applies g first and passes that result to f, so it represents f(g(x)). Choose the direction that makes the transformation and compatible types clearest.Awareness of Function composition methods — shows depth of Java 8 knowledge
Getting the order backwards for compose()
Show with types: f: A→B, g: B→C, f.andThen(g) gives A→C
Interview-ready guide
Interview answer
Both methods combine compatible Functions, but the execution order is opposite. f.andThen(g) runs f first and gives its result to g, so the expression is g(f(x)). f.compose(g) runs g first and gives that result to f, so it is f(g(x)). For example, trim.andThen(toUpperCase) trims and then uppercases. The equivalent ordering can be written toUpperCase.compose(trim). The types must connect: the first result has to be accepted by the second function. Both methods return a new Function and do not modify the original ones. I choose the form that makes the intended data flow easiest to read.
Function.andThen() vs Function.compose()
Direct Answer
f.andThen(g) applies f first and passes its result to g, so it represents g(f(x)). f.compose(g) applies g first and passes that result to f, so it represents f(g(x)). Choose the direction that makes the transformation and compatible types clearest.
Code Example
import java.util.function.Function;
public class AndThenVsCompose {
public static void main(String[] args) {
Function<Integer, Integer> times2 = x -> x * 2;
Function<Integer, Integer> plus3 = x -> x + 3;
// andThen: times2 first, then plus3 -> (5*2)+3
System.out.println(times2.andThen(plus3).apply(5)); // 13
// compose: plus3 first, then times2 -> (5+3)*2
System.out.println(times2.compose(plus3).apply(5)); // 16
}
}
Common Mistakes & Pitfalls
- Reversing
compose:f.compose(g)runsgfirst and thenf. - Ignoring type flow: with
f.andThen(g), the output offmust be compatible with the input accepted byg. - Assuming order cannot change the result: parsing, rounding, validation, and side effects may produce different results when reversed.
- Choosing by novelty: use the direction that makes the intended data flow easiest to verify.
Check your understanding
Answer these without looking back at the article.
- What is the mathematical definition of function composition?
- Can you chain more than two Functions with andThen?
- What types must align when composing Functions?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.