本文将了解java8新特性-foreach 循环List和Map.
Map
- java8前遍历map
1 Map<String, Integer> items = new HashMap<>(); 2 items.put("A", 10); 3 items.put("B", 20); 4 items.put("C", 30); 5 items.put("D", 40); 6 items.put("E", 50); 7 items.put("F", 60); 8 9 for (Map.Entry<String, Integer> entry : items.entrySet()) { 10 System.out.println("Item : " + entry.getKey() + " Count : " + entry.getValue()); 11 }
- java8后
1 Map<String, Integer> items = new HashMap<>(); 2 items.put("A", 10); 3 items.put("B", 20); 4 items.put("C", 30); 5 items.put("D", 40); 6 items.put("E", 50); 7 items.put("F", 60); 8 9 items.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v)); 10 11 items.forEach((k,v)->{ 12 System.out.println("Item : " + k + " Count : " + v); 13 if("E".equals(k)){ 14 System.out.println("Hello E"); 15 } 16 });
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);
Tops:Lambda表达式实质是度函数式接口的实现;