In this post, several methods are discussed to merge multiple sets in Java into a single set using plain Java, Java 8, Guava, and Apache Commons.

Please note that the merge operation will discard duplicate elements present in any set.

1. Using Java 8

We can use streams in Java 8 and above to merge multiple sets by obtaining a stream consisting of all elements from every set using the static factory method Stream.of() and accumulating all elements into a new set using a Collector.

We can also accumulate all elements using forEach(), as shown below:

 
Stream also has a concat() method that takes two streams as input and creates a lazily merged stream out of them. We can use it to merge multiple sets, as shown below:

2. Using Guava’s Iterables

Guava’s Iterables class provides many static utility methods that operate on or return objects of type Iterable.

1. concat() can be used to combine several iterables into a single iterable, as shown below:

 
2. addAll(Iterable, Collection) adds all elements in the specified iterable to the collection. We can use it inside a for-each loop to merge multiple sets, as shown below:

3. Using Apache Commons Collections

Apache Commons Collections SetUtils.union() method takes two sets as an input and returns a new set containing the second set appended to the first set. We can use it to merge multiple sets, as shown below:

 
Apache Commons Collections also provides the IterableUtils class that contains several utility methods for Iterable instances. One such method is chainedIterable(), which can combine multiple Iterables into a single one, as shown below:

4. Using Set.addAll() method

Set.addAll(Collection) method merges all elements of the specified collection to the set (if not already present). We can use it inside a for-each loop to merge multiple sets, as shown below:

5. Using Collections.addAll() method

Collections class provides addAll(Collection, T[]) method that adds specified elements to the specified collection. This method is similar to Set.addAll() but offers better performance.

6. Using Double Brace Initialization

We can also use Double Brace Initialization, which internally creates an anonymous inner class with an instance initializer in it. We should avoid this method at all costs.

That’s all about merging multiple sets in Java.