I have n
maps of the kind:
HashMap<String,Double> map1;
HashMap<String,Double> map2; ...
What could I do to merge all these maps into a single map?
And I want to achieve this without losing the data.
Example:
map1 has entries: {<X1, Y1>, <X2,Y2>, <X3,Y3>}
map2 has entries: {<X1, Y6>, <X2, Y7>, <X3,Y8>}
mergedMap: {<X1, Y1+Y6>, <X2,Y2+Y7>, <X3, Y3+Y8>}
I have tried this:
ArrayList<HashMap<String, Double>> listHashMap = new ArrayList<>();
HashMap<String,Double> mergedMap = new HashMap<>();
for(HashMap<String,Double> map: listHashMap) {
mergedMap.putAll(map);
}
But I've understood that the values mapped to the same key would be replaced (put
), not added.
What could I do to add up each value mapped to the same key?
You can utilize Java 8 method merge()
to combine the data of each entry:
List<Map<String, Double>> list = // initializing source list
Map<String, Double> mergedMap = new HashMap<>();
list.forEach(map -> map.forEach((k, v) -> mergedMap.merge(k, v, Double::sum)));
See that code run live at Ideone.com.
Or you can make use of Stream API with combination of built-in collectors groupingBy()
and summingDouble()
:
Map<String, Double> mergedMap = list.stream()
.flatMap(map -> map.entrySet().stream())
.collect(Collectors.groupingBy(
Map.Entry::getKey, Collectors.summingDouble(Map.Entry::getValue)
));
Take a look at these tutorials provided by Oracle for more information on lambda expressions and streams.