Java 8中BiConsumer使用示例

书欣 Java经验 发布时间:2023-01-29 09:47:42 阅读数:10715 1
下文笔者讲述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));
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202301/16749632065566.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者