How to Convert a List to Set in Java
How can we convert a list to a set in Java?
Suppose we have a list list
, we want to convert this list into a set.
List<T> list = new ArrayList<>();
Note that converting a list to a set will remove duplicates from the collection.
1. Using Set
constructor
The simplest way to convert a list to a set is using the Set
constructor.
Set<T> hashSet = new HashSet<T>(list);
Set<T> treeSet = new TreeSet<T>(list);
The HashSet
returns an unsorted set while the TreeSet
returns a sorted one. However, if list
is null
, this will return a NullPointerException
.
2. Using Set.addAll()
We can also initialize the set and add all the elements later on.
Set<T> set = new HashSet<>();
set.addAll(list);
3. Using Java 8 Streams
With Java 8 streams, we can accumulate the input elements into a new, mutable set.
Set<T> set = list.stream().collect(Collectors.toSet());
Set<T> set = list.stream().collect(Collectors.toCollection(HashSet::new));
This is especially useful if we need to perform some preprocessing on the elements.
If we’re working with a list that may be null
, we can use Optional.ofNullable
and assign the set to null
if the list is null
.
Set<T> set = Optional.ofNullable(list).map(HashSet::new).orElse(null);
4. Using Guava
Guava provides a succinct way to convert a list into a set as well.
Set<T> set = Sets.newHashSet(list);
5. Using Apache Commons Collection
Apache Commons allows us to add elements of a list to some target set.
Set<T> set = new HashSet<>();
CollectionUtils.addAll(set, list);
6. Using Java 10’s Set.copyOf()
In Java 10, we can use copyOf()
to create an unmodifiable set from an existing Collection
or Map
.
Set<T> set = Set.copyOf(list);
Set<T> set = ImmutableSet.copyOf(list);
Any null
elements in the list will throw a NullPointerException
.
Any mutator method called on the set will throw an UnsupportedOperationException
.
Note that
copyOf()
is idempotent. Copying a previously copied collection does not create another copy.