JDK8新特性,map.forEach((key,value)->)的使用

JDK8对Map集合的遍历方式进行了简化。

foreach()方法对HashMap中的每个映射指定执行的操作。

foreach()的语法为:

注意:这里面的key,value是随意起的,也可以是kk,cc;  ff,xx;

map.foreach((key,value)->{action})

遍历如下:

public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "22");
        map.put(2, "weqw");
        map.put(3, "sjemgri");

        map.forEach((f,e)->{
            System.out.println(f + " --  " + e);
        });
    }

遍历结果:

1 --  22
2 --  weqw
3 --  sjemgri

猜你喜欢

转载自blog.csdn.net/Sunshineoe/article/details/115431877
今日推荐