BiConsumer: Accepting Two Arguments
You'll learn how BiConsumer<T, U> extends the consumer pattern to operations that need two inputs instead of one.
The Core Idea
While Consumer<T> accepts a single argument, BiConsumer<T, U> accepts two arguments of potentially different types and performs a side effect with them. Think of it as the two-parameter version of what you already know: instead of "do something with one thing," it's "do something with two things."
The most common real-world use is with Map.forEach, where you need both the key and value to perform an operation.
The BiConsumer Interface
@FunctionalInterface
public interface BiConsumer<T, U> {
void accept(T t, U u);
}
Notice it has two type parameters and its accept method takes two arguments.
Using BiConsumer with Map.forEach
Map<String, Integer> scores = Map.of(
"Alice", 95,
"Bob", 87,
"Charlie", 92
);
// BiConsumer with lambda
BiConsumer<String, Integer> printScore =
(name, score) -> System.out.println(name + ": " + score);
scores.forEach(printScore);
// More commonly, inline:
scores.forEach((name, score) ->
System.out.println(name + " scored " + score));
Chaining BiConsumers
Just like Consumer, you can chain BiConsumer instances:
BiConsumer<String, Integer> logger =
(name, score) -> System.out.println(name + ": " + score);
BiConsumer<String, Integer> validator =
(name, score) -> {
if (score < 60) {
System.out.println(name + " needs improvement");
}
};
scores.forEach(logger.andThen(validator));
Key Takeaway: BiConsumer<T, U> handles operations requiring two inputs and no return value, making it perfect for Map.forEach and other two-argument side-effect scenarios.