Merge Multiple Sets in Java

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 duplicate elements present in any set will be discarded during the merge operation.

 

1. Java 8

We can use streams in Java 8 to merge multiple sets by obtaining a stream consisting of all elements from every set using 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 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. Guava Iterables

Guava 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 specified iterable to collection. We can use it inside a for-each loop to merge multiple sets as shown below:

 

3. 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 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. Set.addAll()

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. Collections.addAll()

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. Double Brace Initialization

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

 
Thanks for reading.




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





Leave a Reply

Notify of
avatar
wpDiscuz