BiConsumer andThen: Sequential Execution
What you'll learn: How to chain multiple BiConsumer operations so they execute one after another on the same two inputs.
The Core Idea
Just like Consumer has an andThen method for chaining single-argument operations, BiConsumer provides the same capability for two-argument operations. This allows you to compose multiple side effects that should happen sequentially on the same pair of inputs.
The andThen method returns a new BiConsumer that first performs the original operation, then performs the second operation. Both operations receive the same two arguments.
How It Works
When you call biConsumer1.andThen(biConsumer2), you create a new BiConsumer that:
- Executes
biConsumer1.accept(t, u) - Then executes
biConsumer2.accept(t, u) - Uses the same values of
tandufor both operations
Think of it like a checklist where each task needs the same two pieces of information. You complete the first task, then the second, using the identical inputs for both.
Example: Processing User Data
BiConsumer<String, Integer> printUser = (name, age) ->
System.out.println("User: " + name);
BiConsumer<String, Integer> printAge = (name, age) ->
System.out.println("Age: " + age);
BiConsumer<String, Integer> combined = printUser.andThen(printAge);
combined.accept("Alice", 30);
// Output:
// User: Alice
// Age: 30
Both operations receive "Alice" and 30, executing in sequence.
Key Takeaway: BiConsumer.andThen() chains two-argument side effects sequentially, allowing you to compose multiple operations that all work on the same pair of inputs without nesting or repetition.