collect–将流转换为其他形式。接受一个Collector接口的实现,用于给stream中元素做汇总的方法
构造测试数据
List<Map<String, String>> list = new ArrayList<>();
Map<String, String> map = new HashMap<>();
map.put("name", "joy");
map.put("age", "23");
list.add(map);
map = new HashMap<>();
map.put("name", "any");
map.put("age", "17");
list.add(map);
map = new HashMap<>();
map.put("name", "angle");
map.put("age", "20");
list.add(map);
- Collectors.toCollection(T :: new)–收集
需要转换成什么类型的集合就通过Collectors.toCollection(T :: new)的方式来构造,T为集合的类名
List<String> nameList = list.stream().map(e -> e.get("name")).collect(Collectors.toList());
nameList.forEach(e ->
System.out.print(e + " ");
});
System.out.println();
HashSet<String> set = list.stream().map(e -> e.get("age")).collect(Collectors.toCollection(HashSet::new));
set.forEach(e -> {
System.out.print(e + " ");
});
outPut : joy any angle
23 17 20
- groupingBy–分组
分组的原理是把这个集合根据我们输入的条件划分为一个个小的集合,将大集合拆分为小集合
//分组
Map<String, List<Map<String, String>>> collect1 = list.stream().collect(Collectors.groupingBy(e -> {
return Integer.parseInt(e.get("age")) > 18 ? "成年" : "未成年";
}));
System.out.println("collect1 : " + collect1);
//多级分组
Map<String, Map<String, List<Map<String, String>>>> collect2 = list.stream().collect(Collectors.groupingBy(e -> {
return Integer.parseInt(e.get("age")) > 18 ? "成年" : "未成年";
}, Collectors.groupingBy(e ->{
return e.get("name").startsWith("a") ? "本地人" : "外地人";
})));
System.out.println("collect2 : " + collect2);
outPut : collect1 : {未成年=[{name=any, age=17}], 成年=[{name=joy, age=23}, {name=angle, age=20}]}
collect2 : {未成年={本地人=[{name=any, age=17}]}, 成年={本地人=[{name=angle, age=20}], 外地人=[{name=joy, age=23}]}}
- partitioningBy-- 分区
将流中的元素分为true和false两片子区域,符合条件的为true,不符合为false
Map<Boolean, List<Map<String, String>>> collect = list.stream().collect(Collectors.partitioningBy(e -> Integer.parseInt(e.get("age")) >= 18));
System.out.println("collect : " + collect);
outPut : collect : {false=[{name=any, age=17}], true=[{name=joy, age=23}, {name=angle, age=20}]}
- 统计
Collectors下面包含summingInt,averagingDouble,joining等类似方法,可以将元素在不同情景下统计为不同的形式
Integer count = list.stream().collect(Collectors.summingInt(e -> Integer.parseInt(e.get("age"))));
System.out.println("count : " + count);
Double avg = list.stream().collect(Collectors.averagingDouble(e -> Integer.parseInt(e.get("age"))));
System.out.println("avg : " + avg);
String collect = list.stream().map(e -> e.get("name")).collect(Collectors.joining(", "));
System.out.println("collect : " + collect);o
utPut : count : 60
avg : 20.0
collect : joy, any, angle