Java Function compose and andThen: Ordering and Usage
Understand the difference between Function.compose and Function.andThen: their execution order, practical examples, and when to use each for readable functional pipelines.

Java's Function interface provides two default methods for composing functions: compose and andThen. Both combine two functions into a new one, but they apply the functions in opposite order. Understanding that order is important for building readable functional pipelines, especially when you chain multiple transformations.
What Are compose and andThen?
Function<T, R> represents a function that accepts one argument of type T and produces a result of type R. The compose and andThen methods let you create a new function by combining two existing ones.
The signatures are:
default <V> Function<V, R> compose(Function<? super V, ? extends T> before)
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after)composereturns a function that first applies the argument function (before) and then applies the original function to the result.andThenreturns a function that first applies the original function and then applies the argument function (after) to the result.
In other words, f.compose(g) is equivalent to f(g(x)), while f.andThen(g) is equivalent to g(f(x)).
Execution Order: compose vs andThen
The key difference is the order in which the two functions execute. This becomes critical when the functions have side effects or when the order of transformations affects the final output.
Consider two simple functions:
Function<Integer, Integer> addOne = x -> x + 1;
Function<Integer, Integer> multiplyByTwo = x -> x * 2;Using compose:
Function<Integer, Integer> composed = addOne.compose(multiplyByTwo);
int result = composed.apply(5); // multiplyByTwo first, then addOne => (5*2)+1 = 11Using andThen:
Function<Integer, Integer> combined = addOne.andThen(multiplyByTwo);
int result = combined.apply(5); // addOne first, then multiplyByTwo => (5+1)*2 = 12The names help: compose means the argument function is composed before the original; andThen means the argument runs after the original. This mirrors the English reading order.
Practical Example: Chaining Functions
A common use case is building a processing pipeline. Suppose you need to trim, transform, and format a string. Instead of nesting calls, you can compose a single function:
Function<String, String> trim = String::trim;
Function<String, String> toUpperCase = String::toUpperCase;
Function<String, String> addPrefix = s -> "Result: " + s;
Function<String, String> pipeline = trim.andThen(toUpperCase).andThen(addPrefix);
String output = pipeline.apply(" hello "); // "Result: HELLO"Here, andThen reads naturally from left to right: trim, then uppercase, then add prefix. Reversing the order with compose would require you to read from right to left, which is less intuitive when the sequence is long.
You can also mix both methods, but the resulting order can be confusing. For example:
Function<String, String> mixed = trim.compose(toUpperCase).andThen(addPrefix);This applies toUpperCase first, then trim, then addPrefix. The execution is addPrefix(trim(toUpperCase(x))). Understanding this requires careful reading.
Handling Null and Errors
Both compose and andThen throw a NullPointerException immediately if the argument function is null. This fail-fast behavior moves the error to composition time instead of delaying it until the composed function is called.
If one of the functions throws an exception, that exception propagates through the composed function. There is no built-in error recovery. For example:
Function<Integer, Integer> divide = x -> 100 / x;
Function<Integer, Integer> addOne = x -> x + 1;
Function<Integer, Integer> composed = divide.andThen(addOne);
try {
composed.apply(0); // ArithmeticException from divide
} catch (ArithmeticException e) {
// handle
}When building pipelines, you may want to handle exceptions at the boundary rather than inside every function. This keeps each function focused on its transformation.
Performance and Runtime Cost
Each call to compose or andThen creates a new Function object that wraps the original functions. This allocation is cheap and usually negligible in typical business logic. However, in performance-critical loops or high-throughput code, creating many composed functions inside a loop can add garbage collection pressure.
A better pattern is to build the composed function once and reuse it:
Function<String, String> pipeline = trim.andThen(toUpperCase).andThen(addPrefix);
for (String s : inputs) {
String result = pipeline.apply(s);
}This avoids repeated allocation. The composed function only holds references to the underlying functions, so it is safe to share across threads as long as the underlying functions are thread-safe.
Choosing Between compose and andThen
The choice depends on how you want to read the code and the order of transformations.
- Use
andThenwhen the natural reading order is left-to-right: first the original function, then the argument. - Use
composewhen you want to apply the argument first, and the original function second, and you prefer the reading order to reflect that.
In practice, andThen is more common because it aligns with the typical flow of data processing. For example, in stream pipelines, map operations are chained left-to-right, and andThen mirrors that.
If you have a base function and want to apply additional steps after it, andThen is clearer. If you are adapting a function to run before an existing one, compose may be more appropriate, but it is often easier to reorder the functions themselves.
Advanced Composition Patterns
Composition also works well with method references. For example:
Function<String, Integer> parse = Integer::parseInt;
Function<Integer, Double> half = n -> n / 2.0;
Function<String, Double> parseAndHalf = parse.andThen(half);You can also create a function that composes a list of steps dynamically. This is useful when the transformation steps are determined at runtime. On Java 9 or later, you can define the steps with List.of:
List<Function<String, String>> steps = List.of(
String::trim,
String::toLowerCase,
s -> s.replace(" ", "_")
);
Function<String, String> combined = steps.stream()
.reduce(Function.identity(), Function::andThen);The reduce operation starts with the identity function and applies each step in order. This pattern keeps the pipeline data-driven and easy to extend.
One limitation to keep in mind: compose and andThen are defined on Function, for unary functions. BiFunction and BinaryOperator do not have the same compose method: BiFunction has an andThen method but no compose, and its signature differs. If you need to chain operations that take multiple arguments, consider converting to a Function by fixing one argument or using a different approach.
Understanding the execution order of compose and andThen is a small but important detail in Java's functional API. Choosing the right method makes your code more readable and prevents subtle bugs when the order of transformations matters.
Try matching browser tools
All toolsSmall utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Java guides
All Java guidesJava Final Keyword: Usage and Behavior
How Java's final keyword works for variables, methods, and classes, with practical examples and decision guidance for using it.
Java Final Variable: Syntax, Behavior, and Use Cases
Understand what a final variable in Java means, how initialization works, and when to use it for constants, immutability, and clearer code.
Java Duration vs Period: When to Use Each
java duration vs period: Compare Java Duration and Period to handle time-based and date-based calculations correctly. Learn syntax, conversion, and pitfalls.
Instance vs Static Variables in Java: Key Differences
Understand the difference between instance and static variables in Java, including memory, lifecycle, and when to use each.
More in Java
All Java guidesThe guides filed next to this one in Java, in library order.