Convert an Array to a Set in Java

In this post, we will see how to convert an array to a Set using plain Java, Guava and Apache Commons Collections. Please note that no duplicate elements are allowed in the array or duplicate will be discarded in set.


 

There are three general-purpose Set implementations in Java — HashSet, TreeSet, and LinkedHashSet. In this post, we’ll be using HashSet, which is very fast and offers constant-time operations.

 

1. Naive

Naive solution would be to create an empty set and push every element of the specified array into the set.

Java

Download   Run Code

Output:

[A, B, C, D]

 

2. Arrays.asList() –

We can pass fixed-size list returned by Arrays.asList() to HashSet constructor to get a mutable set.

Java

Download   Run Code

Output:

[A, B, C, D]

 

3. Collections.addAll() –

We can use Collections.addAll() provided by Java SE or CollectionUtils.addAll() provided by Apache Commons Collections to add all elements of the specified array to the specified set as shown below:

 

Download   Run Code

 

4. Java 8 –

In Java 8, we can use Stream API to convert an array to a set. The idea is to first convert the specified array to a sequential Stream using Arrays.stream() or Stream.of() and then use a Collector to accumulate the input elements into a new Set.

Java8

Download   Run Code

Output:

[A, B, C, D]

We can use Collectors.toCollection() to specify the desired Collection as Collectors.toSet() doesn’t guarantees on the type of the Set returned.

Download   Run Code

 

5. Guava –

We can also use the Guava API to convert an array to a set.

1. Sets.newHashSet() creates a mutable HashSet instance containing the given elements. This method should be used if you need to add or remove elements later or some of the elements can be null.

Download   Run Code

 
2. We can also use ImmutableSet.copyOf or ImmutableSet.of() that returns an immutable set containing the elements of the specified array. These should be preferred where mutability is not required.

Download   Run Code

 
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 🙂
 


Get great deals at Amazon




Leave a Reply

Notify of
avatar
wpDiscuz