Java List<Map<String, Long>> sum of group by of map key

▼魔方 西西 提交于 2019-12-21 23:17:08

问题


I have a: List<Map<String, Long>> items = new ArrayList<>();

I would like to get a Map in which the key is grouped by, and the value is the sum.

Example: List

  • Item 0
    • foo -> 1
    • bar -> 2
  • Item 1
    • foo -> 4
    • bar -> 3

Result: Map

  • foo -> 5
  • bar -> 5

I know how to do this the "long" way, but was trying to discover a lambda/streaming/groupby approach using the java 8 features. any thoughts?


回答1:


You can use groupingBy collector:

import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.summingLong;

items.stream()
        .flatMap(m -> m.entrySet().stream())
        .collect(groupingBy(Map.Entry::getKey, summingLong(Map.Entry::getValue)));

Or you can use toMap:

import static java.util.stream.Collectors.toMap;

items.stream()
        .flatMap(m -> m.entrySet().stream())
        .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, Long::sum));


来源:https://stackoverflow.com/questions/34325389/java-listmapstring-long-sum-of-group-by-of-map-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!