Course contentsShow
← Java
Lesson 1678 of 2,87035. Functional InterfacesFree lesson

BiConsumer andThen: Sequential Execution

Chain multiple BiConsumer operations to perform sequential side effects.

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:

  1. Executes biConsumer1.accept(t, u)
  2. Then executes biConsumer2.accept(t, u)
  3. Uses the same values of t and u for 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.