This post will discuss 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 duplicates will be discarded in the set.

There are three general-purpose set implementations in Java — HashSet, TreeSet, and LinkedHashSet. This post will be using HashSet, which is very fast and offers constant-time operations.

1. Naive solution

A naive solution is to create an empty set and push every element of the specified array into the set.

Download  Run Code

Output:

[A, B, C, D]

2. Using Arrays.asList() method

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

Download  Run Code

Output:

[A, B, C, D]

3. Using Collections.addAll() method

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. Using Java 8

In Java 8, we can use the Stream to convert an array to a set. The idea is first to 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.

Download  Run Code

Output:

[A, B, C, D]

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

Download  Run Code

5. Using Guava Library

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

1. Sets.newHashSet() creates a mutable HashSet instance containing the given elements. We should use this method 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

That’s all about converting an array to a Set in Java.