BiFunction andThen: Composing After Results
You'll learn how to chain a BiFunction with a Function to transform the combined result into something else.
The Core Idea
A BiFunction<T, U, R> takes two inputs and produces one result. But what if you want to immediately transform that result further? The andThen method lets you attach a Function<R, V> that processes the output, creating a pipeline: two inputs → intermediate result → final result.
Think of it like a factory assembly line: BiFunction combines two raw materials into a product, then andThen adds a finishing step (like painting or packaging) before delivery.
How It Works
The signature is straightforward:
BiFunction<T, U, R> original = ...;
Function<R, V> postProcessor = ...;
BiFunction<T, U, V> composed = original.andThen(postProcessor);
When you call composed.apply(t, u), it internally:
- Executes
original.apply(t, u)to get resultR - Passes that result to
postProcessor.apply(r)to get final resultV
Practical Example
BiFunction<String, String, String> concat = (a, b) -> a + b;
Function<String, Integer> getLength = String::length;
BiFunction<String, String, Integer> concatAndMeasure = concat.andThen(getLength);
int result = concatAndMeasure.apply("Hello", "World"); // 10
Here, concat joins two strings, then getLength measures the combined result.
Why Use andThen?
It keeps your code declarative and composable. Instead of nesting operations manually, you build a clear transformation pipeline that's easier to read and reuse.
Key Takeaway: BiFunction.andThen(Function) lets you chain a post-processing step onto your two-argument operation, transforming the combined result before returning it.