collect方法
收集(collect)
collect,收集,可以说是内容最繁多、功能最丰富的部分了。从字面上去理解,就是把一个流收集起来,最终可以是收集成一个值也可以收集成一个新的集合。
collect主要依赖java.util.stream.Collectors类内置的静态方法。
归集(toList/toSet/toMap)
因为流不存储数据,那么在流中的数据完成处理后,需要将流中的数据重新归集到新的集合里。 toList、toSet和toMap比较常用,另外还有toCollection、toConcurrentMap等复杂一些的用法。
List
Set
List
Map personMap =
personList.stream().filter(p -> p.getSalary() > 8000).collect(Collectors.toMap(Person::getName,
p -> p));
System.out.println(“产生的新的map集合是:” + personMap);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
统计(count/averaging)
Collectors提供了一系列用于数据统计的静态方法:
计数:count
平均值:averagingInt、averagingLong、averagingDouble
最值:maxBy、minBy
求和:summingInt、summingLong、summingDouble
统计以上所有:summarizingInt、summarizingLong、summarizingDouble
1
2
3
4
5
/*
* 案例:统计员工人数、平均工资、工资总额、最高工资。
/
// 求总数
Long count = personList.stream().collect(Collectors.counting());
System.out.println(“员工总数:” + count);
// 求平均工资
Double avgSalary = personList.stream().collect(Collectors.averagingDouble(Person::getSalary));
System.out.println(“员工平均工资:” + avgSalary);
// 求工资之和
Integer sumSalary = personList.stream().collect(Collectors.summingInt(Person::getSalary));
System.out.println(“员工工资总和:” + sumSalary);
// 一次性统计所有信息
DoubleSummaryStatistics collect = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));
System.out.println(“员工工资所有统计:” + collect);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
分组(partitioningBy/groupingBy)
分区:将stream按条件分为两个Map,比如员工按薪资是否高于8000分为两部分。
分组:将集合分为多个Map,比如员工按性别分组。有单级分组和多级分组。
1
2
/*
* 案例:将员工按薪资是否高于8000分为两部分;将员工按性别和地区分组
/
// 将员工按薪资是否高于8000分组
Map
String names = personList.stream().map(p -> p.getName()).collect(Collectors.joining(“,”));
System.out.println(“所有员工的姓名:” + names);
List
// 每个员工减去起征点后的薪资之和
Integer sumsal = personList.stream().collect(Collectors.reducing(0, Person::getSalary, (x, y) -> x + y – 5000));
System.out.println(“员工扣税薪资总和:” + sumsal);
// stream的reduce
Integer sum = personList.stream().map(Person::getSalary).reduce(0, (x, y) -> x + y – 5000);
System.out.println(“—-员工扣税薪资总和:” + sum);
1
2
3
4
5
6
排序(sorted)
sorted,中间操作。有两种排序:
sorted():自然排序,流中元素需实现Comparable接口
sorted(Comparator com):Comparator排序器自定义排序
1
2
/*
* 案例:将员工按工资由高到低(工资一样则按年龄由大到小)排序
/
// 按工资升序排序(自然排序)
List
// 先按工资再按年龄升序排序
List
// 先按工资再按年龄自定义排序(降序)
List
String[] arr1 = {“a”, “b”, “c”, “d”};
String[] arr2 = {“d”, “e”, “f”, “g”};
Stream
// concat:合并两个流 distinct:去重
List
Original: https://www.cnblogs.com/ExMan/p/16386495.html
Author: ExplorerMan
Title: Java8新特性之Stream–collect方法
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/537799/
转载文章受原作者版权保护。转载请注明原作者出处!