What is the easiest way to convert a List
to a Set
in Java?
16 Answers
I agree with sepp2k, but there are some other details that might matter:
new HashSet<Foo>(myList);
will give you an unsorted set which doesn't have duplicates. In this case, duplication is identified using the .equals() method on your objects. This is done in combination with the .hashCode() method. (For more on equality look here)
An alternative that gives a sorted set is:
new TreeSet<Foo>(myList);
This works if Foo implements Comparable. If it doesn't then you may want to use a comparator:
Set<Foo> lSet = new TreeSet<Foo>(someComparator);
lSet.addAll(myList);
This depends on either compareTo() (from the comparable interface) or compare() (from the comparator) to ensure uniqueness. So, if you just care about uniqueness, use the HashSet. If you're after sorting, then consider the TreeSet. (Remember: Optimize later!) If time efficiency matters use a HashSet if space efficiency matters, look at TreeSet. Note that more efficient implementations of Set and Map are available through Trove (and other locations).
If you use the Guava library:
Set<Foo> set = Sets.newHashSet(list);
or, better:
Set<Foo> set = ImmutableSet.copyOf(list);
Set<E> alphaSet = new HashSet<E>(<your List>);
or complete example
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ListToSet
{
public static void main(String[] args)
{
List<String> alphaList = new ArrayList<String>();
alphaList.add("A");
alphaList.add("B");
alphaList.add("C");
alphaList.add("A");
alphaList.add("B");
System.out.println("List values .....");
for (String alpha : alphaList)
{
System.out.println(alpha);
}
Set<String> alphaSet = new HashSet<String>(alphaList);
System.out.println("\nSet values .....");
for (String alpha : alphaSet)
{
System.out.println(alpha);
}
}
}
Let's not forget our relatively new friend, java-8 stream API. If you need to preprocess list before converting it to a set, it's better to have something like:
list.stream().<here goes some preprocessing>.collect(Collectors.toSet());
There are various ways to get a Set
as:
List<Integer> sourceList = new ArrayList();
sourceList.add(1);
sourceList.add(2);
sourceList.add(3);
sourceList.add(4);
// Using Core Java
Set<Integer> set1 = new HashSet<>(sourceList); //needs null-check if sourceList can be null.
// Java 8
Set<Integer> set2 = sourceList.stream().collect(Collectors.toSet());
Set<Integer> set3 = sourceList.stream().collect(Collectors.toCollection(HashSet::new));
//Guava
Set<Integer> set4 = Sets.newHashSet(sourceList);
// Apache commons
Set<Integer> set5 = new HashSet<>(4);
CollectionUtils.addAll(set5, sourceList);
When we use Collectors.toSet()
it returns a set and as per the doc:There are no guarantees on the type, mutability, serializability, or thread-safety of the Set returned
. If we want to get a HashSet
then we can use the other alternative to get a set (check set3
).
With Java 10, you could now use Set#copyOf
to easily convert a List<E>
to an unmodifiable Set<E>
:
Example:
var set = Set.copyOf(list);
Keep in mind that this is an unordered operation, and null
elements are not permitted, as it will throw a NullPointerException
.
If you wish for it to be modifiable, then simply pass it into the constructor a Set
implementation.
If you use Eclipse Collections:
MutableSet<Integer> mSet = Lists.mutable.with(1, 2, 3).toSet();
MutableIntSet mIntSet = IntLists.mutable.with(1, 2, 3).toSet();
The MutableSet
interface extends java.util.Set
whereas the MutableIntSet
interface does not. You can also convert any Iterable
to a Set
using the Sets
factory class.
Set<Integer> set = Sets.mutable.withAll(List.of(1, 2, 3));
There is more explanation of the mutable factories available in Eclipse Collections here.
If you want an ImmutableSet
from a List
, you can use the Sets
factory as follows:
ImmutableSet<Integer> immutableSet = Sets.immutable.withAll(List.of(1, 2, 3))
Note: I am a committer for Eclipse Collections
Remember that, converting from List to Set will remove duplicates from collection because List supports duplicates but Set does not support duplicates in Java.
Direct Conversion : The most common and simple way to convert a List to a Set
// Creating a list of strings
List<String> list = Arrays.asList("One", "Two", "Three", "Four");
// Converting a list to set
Set<String> set = new HashSet<>(list);
Apache Commons Collections : You may also use the Commons Collections API to convert a List to a Set :-
// Creating a list of strings
List<String> list = Arrays.asList("One", "Two", "Three", "Four");
// Creating a set with the same number of members in the list
Set<String> set = new HashSet<>(4);
// Adds all of the elements in the list to the target set
CollectionUtils.addAll(set, list);
Using Stream : Another way is to convert given list to stream, then stream to set :-
// Creating a list of strings
List<String> list = Arrays.asList("One", "Two", "Three", "Four");
// Converting to set using stream
Set<String> set = list.stream().collect(Collectors.toSet());