Skip to content

Easiest way to convert a List to a Set in Java

To convert a List to a Set in Java, you can use the new HashSet<>(list) constructor to create a new HashSet and initialize it with the elements of the List. Here's an example of how to use this constructor to convert a List to a Set:


java
import java.util.List;
import java.util.Set;
import java.util.HashSet;

public class Main {
    public static void main(String[] args) {
        List<String> list = List.of("apple", "banana", "cherry");
        Set<String> set = new HashSet<>(list);
        System.out.println(set);  // output: [apple, banana, cherry]
    }
}

This will create a new HashSet and add all the elements of the List to the set. The HashSet class does not allow duplicate elements, so any duplicates in the List will be removed when the set is created.

Alternatively, you can use the addAll method of the Set interface to add all the elements of the List to an existing set. For example:


java
Set<String> set = new HashSet<>();
set.addAll(list);

This will add all the elements of the List to the Set.

Either way, this is a simple and efficient way to convert a List to a Set in Java. Both methods are widely used and perform well for most use cases.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.