You can create a custom addALL
method to combine the entries of two maps and inside them the elements of two collections:
/**
* Combines the entries of several maps into the {@link TreeMap}
* and the elements of sets inside them into the {@link TreeSet}.
*
* @param maps the collection of maps to be combined
* @param <T> the type of keys of maps
* @param <U> the type of elements of sets
* @return combined map of sets
*/
public static <T, U> Map<T, Set<U>> addAll(Collection<Map<T, Set<U>>> maps) {
return maps.stream()
// Stream<Map.Entry<String,Set<Integer>>>
.flatMap(map -> map.entrySet().stream())
// stream of map entries into one map
.collect(Collectors.toMap(
// key is the same
Map.Entry::getKey,
// value is the same
Map.Entry::getValue,
// combining elements of two collections
(set1, set2) -> Stream.concat(set1.stream(), set2.stream())
// collectionFactory
.collect(Collectors.toCollection(TreeSet::new)),
// mapFactory
TreeMap::new));
}
// test
public static void main(String[] args) {
Map<String, Set<Integer>>
map1 = Map.of("one", Set.of(1, 2, 3), "two", Set.of(1, 2, 3)),
map2 = Map.of("one", Set.of(4, 5, 6), "two", Set.of(4, 5, 6)),
// combine the entries of two maps into one map
map3 = addAll(Set.of(map1, map2));
// output
System.out.println(map3);
// {one=[1, 2, 3, 4, 5, 6], two=[1, 2, 3, 4, 5, 6]}
}
See also: How do I take the union of sets?