在Java8中,BiConsumer
是一个函数式接口。它可以接受两个参数,没有返回值。
@FunctionalInterface
public interface BiConsumer<T, U> {
void accept(T t, U u);
}
进一步阅读:Java8函数式接口Consumer使用教程
例子1: 基本用法
首先来看一下BiConsumer
最基本的用法。
JavaBiConsumer1.java
package cc.myexample.java8;
import java.util.function.Consumer;
public class JavaBiConsumer1 {
public static void main(String[] args) {
BiConsumer<Integer, Integer> addTwo = (x, y) -> System.out.println(x + y);
addTwo.accept(1, 2); // 3
}
}
输出
3
例子2: 高阶函数
在下面的代码中BiConsumer
会被作为参数传递,创建一个通用的addTwo
函数用于连接两个对象。
JavaBiConsumer2.java
package cc.myexample.java8;
import java.util.function.BiConsumer;
public class JavaBiConsumer2 {
public static void main(String[] args) {
addTwo(1, 2, (x, y) -> System.out.println(x + y)); // 3
addTwo("Node", ".js", (x, y) -> System.out.println(x + y)); // Node.js
}
static <T> void addTwo(T a1, T a2, BiConsumer<T, T> c) {
c.accept(a1, a2);
}
}
输出
3
Node.js
再来看一个稍微”高级“一点的例子,下面的代码实现了加减乘除:
JavaBiConsumer3.java
package cc.myexample.java8;
import java.util.function.BiConsumer;
public class JavaBiConsumer3 {
public static void main(String[] args) {
math(1, 1, (x, y) -> System.out.println(x + y)); // 2
math(1, 1, (x, y) -> System.out.println(x - y)); // 0
math(1, 1, (x, y) -> System.out.println(x * y)); // 1
math(1, 1, (x, y) -> System.out.println(x / y)); // 1
}
static <Integer> void math(Integer a1, Integer a2, BiConsumer<Integer, Integer> c) {
c.accept(a1, a2);
}
}
输出
2
0
1
1
例子3: Map.forEach
如下所示,JDK中的Map.forEach
也是接受一个BiConsumer
作为参数,传入的第一个参数是Key
,第二个参数是Value
:
Map.java
default void forEach(BiConsumer<? super K, ? super V> action) {
Objects.requireNonNull(action);
for (Map.Entry<K, V> entry : entrySet()) {
K k;
V v;
try {
k = entry.getKey();
v = entry.getValue();
} catch (IllegalStateException ise) {
// this usually means the entry is no longer in the map.
throw new ConcurrentModificationException(ise);
}
action.accept(k, v);
}
}
下面这个例子演示了Map.forEach
的使用,它可以输出Map
中的Key
与对应的Value
到屏幕上。
JavaMapBiConsumer.java
package cc.myexample.java8;
import java.util.LinkedHashMap;
import java.util.Map;
public class JavaMapBiConsumer {
public static void main(String[] args) {
Map<Integer, String> map = new LinkedHashMap<>();
map.put(1, "Java");
map.put(2, "C++");
map.put(3, "Rust");
map.put(4, "JavaScript");
map.put(5, "Go");
map.forEach((k, v) -> System.out.println(k + ":" + v));
}
}
输出
1:Java
2:C++
3:Rust
4:JavaScript
5:Go