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

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

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
复制代码

forEach 使用方式

复制代码
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
复制代码
复制代码
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 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 使用方式

复制代码
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));
复制代码
原文地址:https://www.cnblogs.com/keyi/p/10482791.html