public static void main(String[] args) {
//添加测试数据
List<Map<String,Object>> drugsInfoList = new ArrayList<>();
Map<String, Object> drugs = new HashMap<String, Object>();
drugs.put("CommonName", 11);
drugs.put("Count", 55);
drugsInfoList.add(drugs);
//添加测试数据
Map<String, Object> drugs2 = new HashMap<String, Object>();
drugs2.put("CommonName", 11);
drugs2.put("Count", 100);
drugsInfoList.add(drugs2);
//添加测试数据
Map<String, Object> drugs3 = new HashMap<String, Object>();
drugs3.put("CommonName", 22);
drugs3.put("Count", 100);
drugsInfoList.add(drugs3);
//现在这段代码只实现根据CommonName去重 现在需求去重之后要把Count的值求和 比如两个CommonName 相同的Map 把他俩只留一个 且Count的值是他俩Count的sum
//现在执行结果[{Count=100, CommonName=22}, {Count=100, CommonName=11}]
//期望[{Count=100, CommonName=22}, {Count=155, CommonName=11}]
List<Map<String, Object>> result = drugsInfoList.stream().collect(Collectors.groupingBy(group -> group.get("CommonName")
.toString())).entrySet().stream().map(map -> {
Map<String, Object> collect = map.getValue().stream().flatMap(o -> o.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (m1, m2) -> m2));
return collect;
}).collect(Collectors.toList());
System.out.println(result);
}
java一个集合去重求和问题 有没有解
最新推荐文章于 2023-01-09 11:40:57 发布