Ben*_*Ben 4 java dictionary hashmap java-8
我有一张地图清单。所有地图都具有相同的键。现在,我想通过汇总每个键的值,将列表的所有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);
}
Run Code Online (Sandbox Code Playgroud)
我经常运行此聚合,因此运行时非常重要...
你可以这样做
Map<Integer, Long> numToSumMap = list_of_maps.stream()
.flatMap(m -> m.entrySet().stream())
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.summingLong(Map.Entry::getValue)));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
74 次 |
| 最近记录: |