how to union 2 maps into one with collection in value
JavaScript
x
HashMap<String, Collection<Integer>> map1 = new HashMap<String, Collection<Integer>>();
HashMap<String, Collection<Integer>> map2 = new HashMap<String, Collection<Integer>>();
map3 = new HashMap<>();
map3.putAll(map1);
map3.putAll(map2);
this way it will override the value
Advertisement
Answer
JavaScript
return Stream.concat(map1.entrySet().stream(), map2.entrySet().stream())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(ids1, ids2) -> {
final Set<Integer> merged = new HashSet<>(ids1);
merged.addAll(ids2);
return merged;
}));
}