This post will discuss how to convert a list to a set in Java. As the set collection contains no duplicate elements, it will discard any repeated elements in the list.

There are three general-purpose implementations of the Set interface provided by JDK — HashSet, TreeSet, and LinkedHashSet. This post uses HashSet, which is very fast and offers constant-time operations.

1. Naive solution

A naive solution is to create an empty set and add every element of the specified list to it.

2. Using Constructor

We can use the HashSet constructor, which can take another collection object to construct a new set containing the elements of the specified list.

 
The constructor will throw NullPointerException if the specified list is null. We can also use TreeSet that gives a sorted set:

 
This only works if all the list elements implement the Comparable interface and are mutually comparable, i.e., for any pair of elements (a, b) in the list, a.compareTo(b) does not throw a ClassCastException.

If all elements of the list don’t implement Comparable, then we can specify our own Comparator. For this method to work, all the list elements must be mutually comparable using the specified comparator.

3. Using Java 8

In Java 8, we can use the Stream to convert a list to a set by converting the specified list to a sequential Stream using List.stream() and using a Collector to accumulate the input elements into a new Set.

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

4. Using Guava Library

We can also use Guava API to convert a list to a set.

1. Sets.newHashSet() creates a mutable HashSet instance containing the specified list elements. We should use this method to add or remove elements later, or some of the elements can be null.

 
2. We can also use ImmutableSet.copyOf that returns an immutable set containing the specified list elements. This should be preferred when mutability is not required.

 
3. Guava also provides TreeSet implementation, which we can use to create a mutable, empty TreeSet instance sorted according to a Comparator provided at set creation time. We can pass Guava’s Ordering.natural() for the natural ordering of keys.

That’s all about converting List to Set in Java.