Merge Two Sets in Java

In this post, we will see 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. Set.addAll()

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

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

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

 

2. Double Brace Initialization

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

 

3. Collections.addAll()

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

 

4. Java 8 – Stream.of() + flatMap() + Collector

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

 

5. Java 8 – Stream.of() + Stream.forEach()

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

 

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

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. Guava Iterables

Guava Iterables class provide concat() method can be used to combine two iterables into a single iterable.

We can also use addAll() method provided by Iterables class that adds all elements in iterable to collection. This can be used in the similar way as Collections's addAll() method.

 

8. Apache Commons Collections

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

 
 
Exercise: Merge Multiple Sets in Java

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz