【发布时间】:2019-05-15 08:21:54
【问题描述】:
我有一个地图列表。所有地图都有相同的键。现在我想通过汇总每个键的值来将列表的所有地图聚合到一个地图。
感觉应该有更好的方法来做到这一点。
// 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);
}
我经常运行这个聚合,所以运行时真的很重要...
【问题讨论】:
-
Counter/numRecordsEachSubpartition是从哪里来的? -
如果性能是最重要的考虑因素,我会坚持使用您现在拥有的解决方案,而不是使用有一些开销的 Streams。
-
我假设
aggr_map和numRecordsEachSubpartition应该是相同的Map,对吧? -
sry,我混淆了命名 -.- 现在修复它!
-
aggr_map是否需要是全新的地图,或者是否可以将元素添加到列表中的现有地图之一?
标签: java dictionary java-8 hashmap