Let’s talk about BiConsumer<T, U>
— it’s part of the java.util.function
package and is a functional interface used when you want to perform an action with two inputs and return nothing.
✅ BiConsumer<T, U>
@FunctionalInterface
public interface BiConsumer<T, U> {
void accept(T t, U u);
}
It takes two arguments: T
and U
Returns void
It’s often used when you want to consume a pair of values (like a key and value), but you don’t need a result
🧠 Example:
BiConsumer<String, Integer> printNameAge = (name, age) ->
System.out.println(name + " is " + age + " years old");
printNameAge.accept("Alice", 30);
// Output: Alice is 30 years old
🔧 Common Use Case: Iterating over a Map
Map<String, Integer> ages = Map.of("Bob", 25, "Carol", 32);
ages.forEach((name, age) -> System.out.println(name + " => " + age));
// Under the hood, this uses a BiConsumer<String, Integer>
🔗 Chaining BiConsumers
You can chain two BiConsumer
s using .andThen()
:
BiConsumer<String, String> greet = (first, last) ->
System.out.print("Hello, " + first + " " + last);
BiConsumer<String, String> shout = (first, last) ->
System.out.println("!!!");
greet.andThen(shout).accept("John", "Doe");
// Output: Hello, John Doe!!!
✅ Summary
Interface | Input Types | Return Type | Use Case Example |
---|---|---|---|
BiConsumer<T,U> | T, U | void | Map.forEach((k, v) -> ...) , logging |