Atitit 集合分组聚合操作sum count avg java版本groovy版本
目录
2.1. Step1 groupby returns Map<grpbyKey, List> 4
2.2. Step2 transform List into Map,key is grpbyKey,value is sumAvgListMapProp 4
- //按性别统计用户数
- Map<User.Sex, Integer> map = users.parallelStream().collect(
- Collectors.groupingBy(User::getGender,
- Collectors.summingInt(p -> 1)));
- System.out.println(map);
- //按性别获取用户名称
- Map<User.Sex, List<String>> map2 = users.stream()
- .collect(
- Collectors.groupingBy(
- User::getGender,
- Collectors.mapping(User::getName,
- Collectors.toList())));
- System.out.println(map2);
- //按性别求年龄的总和
- Map<User.Sex, Integer> map3 = users.stream().collect(
- Collectors.groupingBy(User::getGender,
- Collectors.reducing(0, User::getAge, Integer::sum)));
- System.out.println(map3);
- //按性别求年龄的平均值
- Map<User.Sex, Double> map4 = users.stream().collect(
- Collectors.groupingBy(User::getGender,
- Collectors.averagingInt(User::getAge)));
- System.out.println(map4);
- // 注意,reduce操作每处理一个元素总是创建一个新值,
- // Stream.reduce适用于返回单个结果值的情况
- //获取所有用户的平均年龄
- private static void reduceAvg() {
- // mapToInt的pipeline后面可以是average,max,min,count,sum
- double avg = users.parallelStream().mapToInt(User::getAge)
- .average().getAsDouble();
- System.out.println("reduceAvg User Age: " + avg);
- }
- //获取所有用户的年龄总和
- private static void reduceSum() {
- double sum = users.parallelStream().mapToInt(User::getAge)
- .reduce(0, (x, y) -> x + y); // 可以简写为.sum()
- System.out.println("reduceSum User Age: " + sum);
- }
def errorCodeList = [
[code: "code1", language: 2, content: "aaa"],
[code: "code1", language: 4, content: "bbbb"],
[code: "code2", language: 3, content: "ccc"],
]
// first groupBy, which returns Map<grpbyKey, List>
def b = errorCodeList.groupBy {
it.code
}.collect {
//Entries
// ...and transform List into Map
code, List value ->
def line=[(code): value.sum { e->e.language }]
return line
//return a map
}
//[code1:6, code2:3]
println b
JDK1.8聚合操作.mhtml