java8新特性forEach在Map和List的应用

时间:2024-04-15 14:05:15

转自:https://www.cnblogs.com/go-onxp/p/jdk8.html

java8 forEach 在Map和List中的使用

原始的使用

java8新特性forEach在Map和List的应用
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("key:"+entry.getKey()+";value:"+entry.getValue());
}
//output
A---10
B---20
C---30
D---40
E---50
F---60
java8新特性forEach在Map和List的应用

forEach 使用方式

java8新特性forEach在Map和List的应用
items.forEach((k,v)->System.out.println("key : " + k + "; value : " + v));

//output
key : A value : 10
key : B value : 20
key : C value : 30
key : D value : 40
key : E value : 50
key : F value : 60
java8新特性forEach在Map和List的应用
java8新特性forEach在Map和List的应用
items.forEach((k,v)->{
System.out.println("Item : " + k + " Count : " + v);
if("E".equals(k)){
System.out.println("Hello E");
}
}); key : A; value : 10
key : B; value : 20
key : C; value : 30
key : D; value : 40
key : E; value : 50
Hello E
java8新特性forEach在Map和List的应用

java8 List 原先的使用方式

java8新特性forEach在Map和List的应用
List<String> arrayList = new ArrayList<>();
arrayList.add("A");
arrayList.add("B");
arrayList.add("C");
arrayList.add("D");
arrayList.add("E"); for (String item:arrayList){
System.out.println(item);
}
java8新特性forEach在Map和List的应用

java8 forEach 使用方式

java8新特性forEach在Map和List的应用
arrayList.forEach(item->System.out.println(item));

arrayList.forEach(System.out::println);

arrayList.forEach(item->{
if("C".equals(item)){
System.out.println(item);
}
}); arrayList.stream()
.filter(s-> s.contains("B")||s.contains("C"))
.forEach(System.out::println); arrayList.stream()
.filter(s->s.contains("E"))
.findFirst().ifPresent(s -> System.out.println(s));
java8新特性forEach在Map和List的应用

相关文章