f.andThen(g) applies f first and then g, while f.compose(g) applies g first and then f; with the same two functions the order changes the answer.
Function<Integer, Integer> times2 = x -> x * 2;
Function<Integer, Integer> plus3 = x -> x + 3;
System.out.println("times2.andThen(plus3) of 5: " + times2.andThen(plus3).apply(5));
System.out.println("times2.compose(plus3) of 5: " + times2.compose(plus3).apply(5));
times2.andThen(plus3) of 5: 13
times2.compose(plus3) of 5: 16
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-27