Function composition
What you will learn
Function composition combines small operations into a reusable pipeline. For instance, first clean an inventory code, then normalize its case. Java provides composition methods on several functional interfaces, with distinct rules about execution order, short-circuiting, and failure.
- Predict compose and andThen execution order.
- Combine predicates with short-circuit logic and explain side effects.
- Construct a typed pipeline with explicit null and exception behavior.
Use a fresh directory per example. Save as Main.java, compile with javac --release 21 Main.java, then run java Main. Only JDK standard-library dependencies are needed.
Compare composition order
import java.util.*;import java.util.function.*;public class Main {
public static void main(String[] args) { Function<Integer, Integer> add = n -> n + 3; Function<Integer, Integer> doubleIt = n -> n * 2; System.out.println(add.andThen(doubleIt).apply(4)); System.out.println(add.compose(doubleIt).apply(4)); }}Expected output:
1411andThen adds before doubling; compose doubles before adding. Using the same input reveals the ordering difference.
Rules and mental model
For a Function<T,R> f, f.andThen(g) applies f and then g to the result; f.compose(g) applies g before f. Their generic signatures constrain the intermediate types. The composed function is created before it is invoked, so the component operations normally run later. If one function throws during invocation, the later function does not run. Passing a null composition argument is rejected at composition time. Function.identity() supplies an operation returning its argument unchanged. A pipeline need not allocate a new object for each step; that depends on what each component does.
Predicate.and evaluates the right predicate only when the left is true; or evaluates the right only when the left is false. negate reverses the boolean result. Put a null guard before a predicate that dereferences its argument. Consumer.andThen executes the first action and then the second if the first completes normally; it does not automatically compensate for earlier side effects if a later action fails. IntUnaryOperator provides compose and andThen for int operations without a generic Integer boundary. A pure transformation is a design choice: composition does not automatically remove side effects, catch exceptions or make operations thread-safe. Prefer named stages with clear inputs and outputs, especially when errors or state changes matter. These small operations will be reused when learning stream pipelines in the next chapter.
Short-circuit a null-sensitive decision
import java.util.*;import java.util.function.*;public class Main {
public static void main(String[] args) { Predicate<String> present = s -> s != null; Predicate<String> longEnough = s -> s.length() >= 4; Predicate<String> valid = present.and(longEnough); System.out.println(valid.test(null)); System.out.println(valid.test("pen")); System.out.println(valid.test("book")); System.out.println(valid.negate().test("pen")); }}Expected output:
falsefalsetruetrueA null input never reaches longEnough. The combined result can then be negated.
Compose different types into a validation pipeline
import java.util.*;import java.util.function.*;public class Main {
public static void main(String[] args) { Function<String, String> strip = String::strip; Function<String, String> upper = s -> s.toUpperCase(Locale.ROOT); Function<String, Integer> length = String::length; Function<String, Integer> codeLength = strip.andThen(upper).andThen(length); System.out.println(codeLength.apply(" ab7 ")); System.out.println(codeLength.apply(" ")); }}Expected output:
30The first stages produce strings; the final stage changes the result type to Integer. Locale.ROOT makes identifier normalization independent of the default locale.
Observe failure in a sequence of actions
import java.util.*;import java.util.function.*;public class Main {
public static void main(String[] args) { List<String> log = new ArrayList<>(); Consumer<String> first = s -> log.add("received " + s); Consumer<String> reject = s -> { throw new IllegalArgumentException("invalid"); }; Consumer<String> last = s -> log.add("saved " + s); try { first.andThen(reject).andThen(last).accept("A"); } catch (IllegalArgumentException ex) { System.out.println(ex.getMessage()); } System.out.println(log); }}Expected output:
invalid[received A]The first action remains observable, the second fails, and the last is skipped. Composition is not a transaction.
Common mistakes
Do not interchange compose and andThen. Do not assume both predicates always run or that a failed later Consumer undoes an earlier action.
Practice
Build an IntUnaryOperator pipeline that subtracts 2 then triples the result. Combine two IntPredicates to accept inputs between 2 and 5 inclusive. For inputs 1, 2, 5 and 6, print transformed accepted values only.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Function composition — knowledge check
Apply the chapter contracts and reason about Java 21-compatible examples.
Let f add 3 and g double. What is f.andThen(g).apply(4)?
Using the same functions, what is f.compose(g).apply(4)?
When does the right side of a.and(b) execute?
The first Consumer throws during first.andThen(second).accept(x). What happens?
What does Function.identity().apply(item) return for an object item?