Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a Map<String,Map<String,Integer>> to Map<String,Integer> using streams

I would like to convert a Map<String,Map<String,Integer>> to a Map<String,Integer> using Streams.

Here's the catch (and why I can't seem to figure it out):

I would like to group my Integer-Values by the Key-Values of the corresponding Maps. So, to clarify:

I have Entries like those:

Entry 1: ["A",["a",1]]

Entry 2: ["B",["a",2]]

Entry 3: ["B",["b",5]]

Entry 4: ["A",["b",0]]

I want to convert that structure to the following:

Entry 1: ["a",3]

Entry 2: ["b",5]

I think that with the Collectors class and methods like summingInt and groupingBy you should be able to accomplish this. I can't seem to figure out the correct way to go about this, though.

It should be noted that all the inner Maps are guaranteed to always have the same keys, either with Integer-value 0 or sth > 0. (e.g. "A" and "B" will both always have the same 5 keys as one another) Everything I've tried so far pretty much ended nowhere. I am aware that, if there wasn't the summation-part I could go with sth like this:

Map<String,Integer> map2= new HashMap<String,Integer>();
                map1.values().stream().forEach(map -> {
                    map2.putAll(map.entrySet().stream().collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue())));
                });

But how to add the summation part?

like image 820
Proph3cy Avatar asked Jul 29 '19 09:07

Proph3cy


People also ask

How do you convert a map to a string?

We can convert a map to a string in java using two array lists. In this, we first fill the map with the keys. Then, we will use keySet() method for returning the keys in the map, and values() method for returning the value present in the map to the ArrayList constructor parameter.

Can we convert map to stream in java?

Converting complete Map<Key, Value> into Stream: This can be done with the help of Map. entrySet() method which returns a Set view of the mappings contained in this map. In Java 8, this returned set can be easily converted into a Stream of key-value pairs using Set. stream() method.

How do I cast a map to a string in java?

Use Object#toString() . String string = map. toString();


1 Answers

This should work:

First create a Stream of the entries of all the inner maps, and then group the entries by key and sum the values having the same key.

Map<String,Integer> map2 = 
    map1.values()
       .stream()
       .flatMap(m -> m.entrySet().stream()) // create a Stream of all the entries 
                                            // of all the inner Maps
       .collect(Collectors.groupingBy(Map.Entry::getKey,
                                      Collectors.summingInt(Map.Entry::getValue)));
like image 112
Eran Avatar answered Sep 19 '22 21:09

Eran