This post will discuss how to merge two sets in Java using plain Java, Java 8, Guava, and Apache Commons Collections.

Please note that any duplicate element present in the set will be discarded during the merge.

1. Using Set.addAll() method

The Set interface provides the addAll() method that appends all elements of the specified collection at the end of the set. We can use it as:

 
We can prevent an extra call to addAll() by initializing the final set by the first or second set using the HashSet constructor.

 
Here’s a slight variation of the above approach by using streams in Java 8 and above:

2. Using Double Brace Initialization

We can also use Double Brace Initialization to merge two sets, which internally creates an anonymous inner class with an instance initializer in it. But we should best avoid it as it costs an extra class at each usage. It also holds hidden references to the enclosing instance and any captured objects, which may cause problems with serialization or memory leaks.

3. Using Collections.addAll() method

Collections class provides addAll(Collection, T[]) method, which should be preferred over Set.addAll() method as it offers better performance.

4. Using flatMap() method

The idea is to obtain a stream of elements from both sets by using the static factory method Stream.of() and accumulate all elements into a new set using a Collector, as shown below:

5. Using Java 8 Stream.of() with Stream.forEach() method

We can avoid using a Collector by accumulating all elements using forEach() instead, as shown below:

6. Using Java 8 Stream.concat() + Collector

The Java Stream provides concat() that takes two streams as input and creates a lazily concatenated stream whose elements are all the elements of the first stream, followed by all the elements of the second stream.

7. Using Guava’s Iterables

Guava’s Iterables class provides a concat() method that can be used to combine two iterable into a single iterable.

We can also use the addAll() method provided by the Iterables class that adds all elements in iterable to the collection. We can use this similarly as the Collections’s addAll() method.

8. Using Apache Commons Collections

Apache Commons Collections provides the SetUtils class that has the union() method, which takes two sets as an input and returns an unmodifiable view of the union of the sets.

That’s all about merging two sets in Java.

 
Exercise: Merge Multiple Sets in Java