How to sum values of a map that inside another map in java?

半城伤御伤魂 提交于 2019-12-11 06:15:46

问题


I have this map that has another HashMap inside it. How can I sum the values of the inner maps and compare them ?

Also the maps size changeable. So I'm looking for a solution that works every size of the maps.

{Team2={Alex=0, Tom=20}, Team1={John=0, Ammy=9, Monica=1}, Team3{...}, ...}

values of teams --> {Alex=0, Tom=20}, {John=0, Ammy=9, Monica=1} ...

values of these values is --> {0,20}, {0,9,1}...

I just want to sum this values and find the biggest one.

 for(int i = 0 ; i < teamNameList.size() ; i++){
                int sum = sum + teams.get(teamNameList.get(i)).values().values();
            }

回答1:


If you are using java 8, you can use :

long sum = map.values().stream()
        .mapToInt(i -> i.values().stream()
        .mapToInt(m -> m).sum()).sum();



回答2:


You can stream through entries, calculate total for each entry and collect the entries back into a new map, e.g.:

Map<String, Map<String, Integer>> map = new HashMap<>();
Map<String, Integer> data = new HashMap<>();
data.put("Alex", 10);
data.put("Tom", 20);
data.put("John", 30);
map.put("team1", data);

Map<String, Integer> totals = map.entrySet()
    .stream()
    .map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), e.getValue().entrySet().stream().mapToInt(Map.Entry::getValue).sum()))
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

System.out.println(totals);


来源:https://stackoverflow.com/questions/44085387/how-to-sum-values-of-a-map-that-inside-another-map-in-java

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