andThen: Composing Functions Sequentially
What you'll learn: How to chain Function instances together using andThen to create powerful data transformation pipelines.
The Core Idea
The andThen method on the Function interface allows you to combine two functions into a single composite function that applies them in sequence. When you call functionA.andThen(functionB), you create a new function that first applies functionA, then feeds that result into functionB.
Think of it like an assembly line: the first station processes your raw material, and the output immediately moves to the next station for further processing—all in one smooth operation.
How It Works
Function<String, Integer> parseLength = s -> s.length();
Function<Integer, Integer> doubleIt = n -> n * 2;
// Compose them: first get length, then double it
Function<String, Integer> pipeline = parseLength.andThen(doubleIt);
String input = "Hello";
Integer result = pipeline.apply(input); // 5 * 2 = 10
The beauty here is that pipeline is itself a Function, so you can pass it around or chain even more operations.
Chaining Multiple Functions
You can stack multiple andThen calls to build complex pipelines:
Function<String, String> trim = String::trim;
Function<String, String> toUpper = String::toUpperCase;
Function<String, Integer> length = String::length;
Function<String, Integer> fullPipeline =
trim.andThen(toUpper).andThen(length);
fullPipeline.apply(" hello "); // "HELLO".length() = 5
Each stage passes its output as input to the next, creating a clean, readable transformation flow.
Key Takeaway: Use andThen to compose functions sequentially, where the output of one function becomes the input of the next, creating reusable transformation pipelines without nesting multiple apply calls.