Convert List to Set in Java

In this post, we will see how to convert list to set in Java. As Set collection contains no duplicate elements, any repeated elements in the list will be discarded.


 

There are three general-purpose implementations of 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

Naive solution would be to create an empty set and add every element of the specified list to it.

 

2. Constructor

We can make use of 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 elements of the list implements 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 doesn’t implement Comparable, then we can specify our own Comparator. For this method to work, all elements of the list must be mutually comparable using the specified comparator.

 

3. Java 8

In Java 8, we can use Stream API 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. Guava Library

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

1. Sets.newHashSet() creates a mutable HashSet instance containing the elements of the specified list. This method should be used if you need 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 elements of the specified list. 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 which is sorted according to a Comparator provided at set creation time. We can pass Guava’s Ordering.natural() for natural ordering of keys.

 
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