Chaining Consumers with andThen
You'll learn how to combine multiple Consumer operations into a single, sequential chain using the andThen method.
What is andThen?
The Consumer interface provides a default method called andThen that lets you combine multiple consumers into one. When you call andThen(anotherConsumer), it creates a new consumer that first performs the original action, then performs the second action. Both operations execute on the same input.
Think of it like a factory assembly line: one worker stamps the part, then andThen the next worker paints it. The part goes through both stations in sequence.
How It Works
The andThen method signature looks like this:
default Consumer<T> andThen(Consumer<? super T> after)
It returns a new Consumer that performs the first operation, then the second. The original consumers remain unchanged.
Basic Example
Consumer<String> printUpper = s -> System.out.println(s.toUpperCase());
Consumer<String> printLength = s -> System.out.println("Length: " + s.length());
Consumer<String> combined = printUpper.andThen(printLength);
combined.accept("hello");
// Output:
// HELLO
// Length: 5
Chaining Multiple Consumers
You can chain more than two consumers together:
Consumer<String> logInput = s -> System.out.println("Processing: " + s);
Consumer<String> transform = s -> System.out.println("Uppercase: " + s.toUpperCase());
Consumer<String> logComplete = s -> System.out.println("Done with: " + s);
Consumer<String> pipeline = logInput.andThen(transform).andThen(logComplete);
pipeline.accept("test");
// Executes all three operations in order
Key Takeaway: Use andThen to build reusable, composable consumer chains that perform multiple side effects in sequence on the same input, making your code more modular and declarative.