Java 8中BiConsumer使用示例
下文笔者讲述java8中BiConsumer示例的简介说明,如下所示
BiConsumer接口功能
BiConsumer是一个接口 它拥有两个参数,没有任何返回值
BiConsumer接口源码
@FunctionalInterface
public interface BiConsumer<T, U> {
void accept(T t, U u);
}
BiConsumer接口示例
package com.java265.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(88,99); //187
}
}
------运行以上代码,将输出以下信息----
187
BiConsumer
package com.java265.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);
}
}
Map.forEach
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);
}
}
package com.java265.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));
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


