BiConsumer示例
在java8中,BiConsumer是一个函数接口,它接收两个参数,没有返回值
@FunctionalInterface
public interface BiConsumer<T, U> {
void accept(T t, U u);
}
BiConsumer
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
高阶函数
下面示例接收BiConsumer作为参数,创建通用的addTwo来连接两个对象。
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
更多示例
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
Map.foreach
在JDK的源代码中,Map.forEach接收BiConsumer作为参数
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);
}
}
JavaMapBiConsumer.java
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