我有一个 map 列表。所有 map 都有相同的键。现在我想通过对每个键的值求和来将列表的所有映射聚合到一个映射。
感觉应该有更好的方法来做到这一点。
// source
public List<Map<Integer, Long>> list_of_maps = new ArrayList<>();
// destination
private Map<Integer, Long> aggr_map = new HashMap<>();
for(Integer i : list_of_maps.iterator().next().keySet()){
long c = 0;
for(Map<Integer, Long> map : list_of_maps){
c += map.get(i).getCount();
}
aggr_map.put(i, c);
}
我经常运行这个聚合,所以运行时间真的很重要......
最佳答案
你可以这样做,
Map<Integer, Long> numToSumMap = list_of_maps.stream()
.flatMap(m -> m.entrySet().stream())
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.summingLong(Map.Entry::getValue)));
关于java - 将多个 map 聚合为一个 map 的优雅且高效的方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56144661/