I have a set of cards:
Collection<Map<String,Double>> myCol = table.values();
I would like to convert this to a map
Map<String, Double>
so for the match key the values ββare summed. Using a for loop, this is pretty simple:
Map<String, Double> outMap = new HashMap<>(); for (Map<String, Double> map : myCol) { outMap = mergeMaps(outMap, map); }
and mergeMaps() is defined as
mergeMaps(Map<String, Double> m1, Map<String, Double> m2){ Map<String, Double> outMap = new TreeMap<>(m1); m2.forEach((k,v) -> outMap.merge(k,v,Double::sum)); return outMap; }
However, I would like to use streams to get maps from the collection. I tried the following:
Map<String, Double> outMap = new HashMap<>(); myCol.stream().forEach(e-> outMap.putAll(mergeMaps(outMap,e))); return outMap;
This works without a problem. However, can I still improve it? I mean, how can I use collectors in it?
java java-8 java-stream
novice
source share