CKTIS / Java
Function.compose: run the argument function first
`compose` builds a function that runs `before` first and passes its result to the receiving function. `andThen` starts with the receiving function instead.
Version: Java SE 21
Syntax
default <V> Function<V, R> compose(Function<? super V, ? extends T> before)Function.compose is a default instance method on java.util.function.Function<T, R> in Java SE 21. Calling f.compose(g) returns a composed function without running either function. Calling apply(x) on the result works like f.apply(g.apply(x)): g (the before argument) runs first, then f.
If f is a Function<T, R>, the composition is a Function<V, R>. The bound ? super V allows before to accept V or one of its supertypes, and ? extends T allows it to return T or one of its subtypes. That makes the intermediate result suitable as input to f.
With f.andThen(g), the order is reversed: f runs first, then g. When the types fit, g.andThen(f) expresses the same order as f.compose(g).
Passing null as before throws NullPointerException when you call compose. If either function throws during apply, the exception reaches the caller without being wrapped. If before throws, the second function does not run.
Examples
import java.util.function.Function;
public class ComposeExample {
public static void main(String[] args) {
Function<Integer, Integer> twice = n -> n * 2;
Function<Integer, Integer> addOne = n -> n + 1;
Function<Integer, Integer> composed = twice.compose(addOne);
System.out.println(composed.apply(3));
System.out.println(twice.andThen(addOne).apply(3));
}
}Result
8 7
`twice.compose(addOne)` increments `3` to `4`, then doubles it to `8`. `twice.andThen(addOne)` doubles `3` to `6` first, then adds `1` to get `7`.
Related lessons
- Java · Lesson 48 · Intermediate · Version: 2