Mansur Muaz Ekici
Mansur Muaz Ekici

Reputation: 31

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

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

Upvotes: 1

Views: 2919

Answers (2)

Darshan Mehta
Darshan Mehta

Reputation: 30819

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

Upvotes: 3

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59978

If you are using java 8, you can use :

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

Upvotes: 2

Related Questions