使用Stream流分组求和案例

需求: 现有一个User对象,包含有用户名username,性别sex,年龄age,考试分数score。
现在需要对UserList,相同用户名和性别和年龄的人将他们的学科分数相加,算出总分

思路:

  1. 先将userList转换为Map,key为User对象
Map<String, List<User>> collect = userList.stream()  
        .collect(Collectors.groupingBy(o -> {  
            User user = new User().setUserName(o.getUserName()).setSex(o.getSex()).setAge(o.getAge());  
            return JSON.toJSONString(user);  
        }));
  1. 将Map转为List
List<User>= collect.entrySet()  
        .stream()  
        .map(m -> {  
            User mat = JSON.parseObject(m.getKey(), User.class);  
            long scoreSum = m.getValue()  
                    .stream()  
                    .count();  
            return mat.setScoreSum(scoreSum);  
        }).collect(Collectors.toList());

总结:

将需要groupby的字段重新赋值给一个新对象,然后将这个对象序列化后作为key,value为原来的List,然后将该map进行计算后转回List对象并赋值。

posted @ 2024-04-09 14:52  ProsperousEnding  阅读(39)  评论(0编辑  收藏  举报