BiConsumer<T, U>: Two Inputs, No Return
What you'll learn: How to use BiConsumer to perform side effects on two arguments without producing a return value.
The Core Idea
BiConsumer<T, U> is the two-argument version of Consumer<T>. While Consumer accepts one input and returns nothing, BiConsumer accepts two inputs and still returns nothing. It's designed for operations that produce side effects—like printing, logging, updating collections, or modifying state—based on two values.
Think of it like a two-handed task: you need both hands (both arguments) to complete the job, but you're not handing anything back when you're done.
The accept Method
Just as Consumer has accept(T t), BiConsumer has:
void accept(T t, U u)
This method takes two parameters and performs an operation without returning anything.
Basic Lambda Syntax
BiConsumer<String, Integer> printNameAndAge =
(name, age) -> System.out.println(name + " is " + age + " years old");
printNameAndAge.accept("Alice", 30);
// Output: Alice is 30 years old
Common Use Cases
Map iteration:
Map<String, Integer> scores = Map.of("Alice", 95, "Bob", 87);
scores.forEach((name, score) -> System.out.println(name + ": " + score));
Updating data structures:
BiConsumer<List<String>, String> addIfNotPresent =
(list, item) -> {
if (!list.contains(item)) {
list.add(item);
}
};
Logging with context:
BiConsumer<String, Exception> logError =
(message, ex) -> System.err.println(message + ": " + ex.getMessage());
Key Takeaway: BiConsumer<T, U> is perfect for side-effect operations that need two inputs but don't produce a return value—commonly used in map iteration, logging, and state modifications.