I would like to merge two Map with JAVA 8 Stream:
Map> mapGlobal = new HashMap>();
Map
Using foreach over Map can be used to merge given arraylist.
public Map> merge(Map> map1, Map> map2) {
Map> map = new HashMap<>();
map.putAll(map1);
map2.forEach((key , value) -> {
//Get the value for key in map.
ArrayList list = map.get(key);
if (list == null) {
map.put(key,value);
}
else {
//Merge two list together
ArrayList mergedValue = new ArrayList<>(value);
mergedValue.addAll(list);
map.put(key , mergedValue);
}
});
return map;
}