Joining (union) of Sets inside a Set in Java

3.7k Views Asked by At

I have a map where the values are sets of integers. What i'd want to do is to get in the best way possible (using only the Java API would be great) the union of all the sets of Integers.

Map<Long, Set<Integer>> map;

What I thought so far is to loop through the values() of the map and manually add to the big Set:

Set<Integer> bigSet = new HashSet<>();
Iterator<Set<Integer>> iter = map.values().iterator();
while(iter.hasNext())
    bigSet.addAll(iter.next());

Also a collection for the union backed by the map would be great. Unfortunately i am stuck with Java 7.

1

There are 1 best solutions below

3
On BEST ANSWER

On the one hand you could use the new Java 8 fluent interface

import static java.util.stream.Collectors.toSet;

Set<Integer> myUnion = map
        .values()
        .stream()
        .flatMap(set -> set.stream())
        .collect(toSet());

On the other hand I would suggest taking a look at Guava's SetMultimap if you can use external libraries.