Skip to content

how to union 2 map into one with collection in value [closed]

how to union 2 maps into one with collection in value

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

Answer

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;
               }));

}