BiConsumer 是 Java 8 引入的一个函数式接口,属于 java.util.function 包。它表示一个接受两个输入参数且不返回结果的操作。
接口定义
@FunctionalInterface
public interface BiConsumer<T, U> {
void accept(T t, U u);
default BiConsumer<T, U> andThen(BiConsumer<? super T, ? super U> after) {
Objects.requireNonNull(after);
return (l, r) -> {
accept(l, r);
after.accept(l, r);
};
}
}
核心方法
accept(T t, U u)- 抽象方法,执行消费操作
- 接受两个参数(类型分别为 T 和 U)
- 不返回任何值(void)
andThen(BiConsumer<? super T, ? super U> after)- 默认方法,用于组合两个 BiConsumer
- 返回一个新的 BiConsumer,先执行当前的 accept,然后执行 after 的 accept
使用场景
BiConsumer 适用于需要对两个对象进行操作而不关心返回值的场景,例如:
- 遍历 Map 并处理键值对
- 执行需要两个参数的操作
- 组合两个对象的处理逻辑
示例代码
基本用法
BiConsumer<String, Integer> printPair = (name, age) ->
System.out.println(name + " is " + age + " years old");
printPair.accept("Alice", 30); // 输出: Alice is 30 years old
组合 BiConsumer
BiConsumer<String, String> printUpper = (s1, s2) ->
System.out.println(s1.toUpperCase() + " " + s2.toUpperCase());
BiConsumer<String, String> printLower = (s1, s2) ->
System.out.println(s1.toLowerCase() + " " + s2.toLowerCase());
// 组合两个 BiConsumer
BiConsumer<String, String> combined = printUpper.andThen(printLower);
combined.accept("Hello", "World");
// 输出:
// HELLO WORLD
// hello world
遍历 Map
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 30);
ages.put("Bob", 25);
// 使用 BiConsumer 遍历 Map
ages.forEach((name, age) ->
System.out.println(name + " -> " + age));
与相关接口的比较
Consumer<T>: 只接受一个参数BiFunction<T,U,R>: 接受两个参数并返回一个结果ObjIntConsumer<T>: 接受一个对象和一个 int 参数
BiConsumer 是函数式编程中处理两个输入参数的无返回值操作的理想选择。
1457

被折叠的 条评论
为什么被折叠?



