============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);
for (Map.Entry<String, Integer> entry : items.entrySet()) {
System.out.println("Item : " + entry.getKey() + " Count : " + entry.getValue());
}
============forEach + Lambda表达式==========
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);
}
============forEach + Lambda表达式==========
List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");
//输出:A,B,C,D,E
items.forEach(item->System.out.println(item));
//输出 : C
items.forEach(item->{
if("C".equals(item)){
System.out.println(item);
}
});
---------------------
1、利用stream().forEach()循环处理List;
List<String> list = Lists.newArrayList();//新建一个List 用的google提供的Guava package com.google.common.collect;
list.add("1");
list.add("2");
list.add("3");
list.stream().forEach(string ->{
System.out.println(string);
});
运行结果:
1
2
3
2、利用stream().map()处理List,并给另外一个List赋值:
List<String> list1 = Lists.newArrayList();
List<String> list2 = Lists.newArrayList();
list1.add("1");
list1.add("2");
list1.add("3");
list2 = list1.stream().map(string -> {
return "stream().map()处理之后:" + string;
}).collect(Collectors.toList());
list2.stream().forEach(string -> {
System.out.println(string);
});
运行结果:
stream().map()处理之后:1
stream().map()处理之后:2
stream().map()处理之后:3
3、利用stream().filter()处理List,对该List进行过滤处理:
List<String> list1 = Lists.newArrayList();
List<String> list2 = Lists.newArrayList();
list1.add("1");
list1.add("1");
list1.add("2");
list1.add("3");
list2 = list1.stream().filter(s -> s != "1").collect(Collectors.toList());
System.out.println(list2.toString());
运行结果:
[2, 3]
---------------------
原文地址:https://www.cnblogs.com/jtlgb/p/9838009.html