List集合分组求和
适用场景
[{"name":"zhangsan", "grade":90}, {"name":"lisi", "grade":100}, {"name":"zhangsan", "grade":95}]
=>
[{"name":"zhangsan", "grade":185}, {"name":"lisi", "grade":100}]
代码示例
// [{"name":"zhangsan", "grade":90}, {"name":"lisi", "grade":100}, {"name":"zhangsan", "grade":95}]
List<User> userList = new ArrayList<>();
Map<String, User> mergedUsers = userList.stream()
.collect(Collectors.toMap(
User::getName,
Function.identity(),
(existing, replacement) ->
{
existing.setGrade(existing.getGrade() + replacement.getGrade());
return existing;
},
LinkedHashMap::new // 保持插入顺序
));
// [{"name":"zhangsan", "grade":185}, {"name":"lisi", "grade":100}]
Collection<User> values = mergedUsers.values();