本文将了解java8新特性-foreach 循环List和Map.
Map#
java8前遍历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()); }
java8后
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"); } });
list
java8前
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); }
java8后
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,E items.forEach(item->System.out.println(item)); //Output : C items.forEach(item->{ if("C".equals(item)){ System.out.println(item); } }); //method reference //Output : A,B,C,D,E items.forEach(System.out::println); //Stream and filter //Output : B items.stream() .filter(s->s.contains("B")) .forEach(System.out::println);
本文转载自:https://www.cnblogs.com/psyco/p/10593205.html
- 本文固定链接: https://www.coordsoft.com/post/28.html
- 转载请注明: admin 于 生活随想 - zwgu 's world 发表
❤️ 㸔 ِ黃 ِ魸【 73hx.xyz 】偸 ِ啪【 73hx.xyz 】你 ِ慬 ِ的 ❤️