単一のものに複数のマップを集約するエレガントでパフォーマンスの高い方法

ベン:

私は地図のリストを持っています。すべてのマップは同じキーを持っています。今、私はちょうど、各キーの値を合計して1枚の地図にリストのすべてのマップを集約したいと思います。

これを行うには良い方法があるはずのようにそれは感じています。

// 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);
}

私は非常に多くの場合、この集約を実行し、その実行時には、本当に重要です...

ラビンドラRanwala:

あなたは、それがとても好き行うことができます

Map<Integer, Long> numToSumMap = list_of_maps.stream()
    .flatMap(m -> m.entrySet().stream())
    .collect(Collectors.groupingBy(Map.Entry::getKey, 
        Collectors.summingLong(Map.Entry::getValue)));

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=185405&siteId=1