I would like to convert a Map<String,Map<String,Integer>>
to a Map<String,Integer>
using Stream
s.
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 Map
s 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?
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.
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.
Use Object#toString() . String string = map. toString();
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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With