有个对象,具有唯一列id,还有计数列count,想合并集合中的id相同的值,并计算count,对象如下:
@Getter
@Setter
public class UserKeyword {
private String id;
private Integer keywordId;
private String keywordName;
private Long userId;
private Integer count;
private BigDecimal weight;
}
做法一:
Map<String, UserKeyword> map=new HashMap<>();
list.forEach(o->{
String key=o.getId();
UserKeyword userKeyword = map.get(key);
if (!Objects.isNull(userKeyword)) {
o.setCount(o.getCount() + userKeyword.getCount());
}
map.put(key,o);
});
list=new ArrayList<>(map.values());
这个好理解,利用map的key唯一特性,遇到重复的更新
做法二:
list=list(Collectors.toList()).stream().collect(Collectors.toMap(UserKeyword::getId, a -> a, (o1, o2) -> {
o1.setCount(o1.getCount() + o2.getCount());
return o1;
})).values())
自己测试