JDK 8 Lambda 表达式解析Map和List

来源:互联网 发布:淘宝没有盗图投诉 编辑:程序博客网 时间:2024/05/18 07:41

翻译:https://www.mkyong.com/java8/java-8-foreach-examples/

在这篇文章中,我们将会和您分享如何使用Java 8的foreach 和Lamaba表达式解析List和Map.

1. forEach and Map

1.1 一般情况下遍历Map的一般方法.

Map<String, Integer> items = new HashMap<>();items.put("A", 10);items.put("B", 20);items.put("C", 30);items.put("D", 40);items.put("E", 50);items.put("F", 60);for (Map.Entry<String, Integer> entry : items.entrySet()) {System.out.println("Item : " + entry.getKey() + " Count : " + entry.getValue());}

1.2 在 Java 8中, 我们能够遍历 用forEach + lambda 表达式遍历Map .

Map<String, Integer> items = new HashMap<>();items.put("A", 10);items.put("B", 20);items.put("C", 30);items.put("D", 40);items.put("E", 50);items.put("F", 60);items.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));items.forEach((k,v)->{System.out.println("Item : " + k + " Count : " + v);if("E".equals(k)){System.out.println("Hello E");}});

2. forEach and List

2.1 一般情况下遍历List的一般方法

List<String> items = new ArrayList<>();items.add("A");items.add("B");items.add("C");items.add("D");items.add("E");for(String item : items){System.out.println(item);}

2.2 在 Java 8中, 我们能够遍历 forEach + lambda 表达式遍历List.

List<String> items = new ArrayList<>();items.add("A");items.add("B");items.add("C");items.add("D");items.add("E");//lambda//Output : A,B,C,D,Eitems.forEach(item->System.out.println(item));//Output : Citems.forEach(item->{if("C".equals(item)){System.out.println(item);}});//method reference//Output : A,B,C,D,Eitems.forEach(System.out::println);//Stream and filter//Output : Bitems.stream().filter(s->s.contains("B")).forEach(System.out::println);
1 0
原创粉丝点击