What it is and why to use it
Function<T, R> represents a transformation from input T to result R. Building a pipeline from small functions helps separate operations such as trimming a value, measuring it and formatting the result. Composition does not run the operations immediately; apply supplies the input later.
How it works
first.andThen(second) runs first and feeds its result to second. first.compose(before) runs before and then first. Generic input and result types must line up. The arithmetic example deliberately uses operations whose order changes the answer.
Common mistakes and limitations
Do not assume compose reads left to right. Exceptions from either function propagate to the caller; composition does not recover from them or validate external data automatically.
Try it and keep learning
Save the complete example below as Main.java. With a JDK supporting Java 17, compile using javac --release 17 Main.java, then run java Main from the same directory. These examples need only the standard library and fixed input; they do not require packages, files or network access.
Syntax
Function<A, C> combined = first.andThen(second);Examples
Function Composition with andThen and compose
Complete Main.java example — Java 17 or later, without preview features.
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
Function<Integer, Integer> addTwo = number -> number + 2;
Function<Integer, Integer> triple = number -> number * 3;
System.out.println(addTwo.andThen(triple).apply(4));
System.out.println(addTwo.compose(triple).apply(4));
}
}- andThen adds 2 to 4, then triples 6, producing 18.
- compose triples 4 first, then adds 2 to 12, producing 14.
- apply performs the combined calculation. In a text-processing pipeline, the same ordering rule determines whether a length is measured before or after trimming.
- Expected output: 18 14
Best practices
- Choose descriptive operation names.
- Keep a pipeline short enough that its data flow is easy to follow.
Runtime & versions
Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Java Language Specification