Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

What is the easiest way to convert a List to a Set in Java?

1 Answer

0 votes
by (13.1k points)

You can convert a List to a set like this:

// Creating a list of strings

List<String> list = Arrays.asList("Alpha", "Beta", "Delta", "Gamma");

// Converting a list to set

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

Using Common Collections API:

// Creating a list of strings

List<String> list = Arrays.asList("Alpha", "Beta", "Delta", "Gamma");

// 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);

By converting a given list to stream, then stream to set:

// Creating a list of strings 

List<String> list = Arrays.asList("Alpha", "Beta", "Delta", "Gamma"); 

// Converting to set using stream 

Set<String> set = list.stream().collect(Collectors.toSet()); 

Want to learn Java? Check out the core Java certification from Intellipaat.

Browse Categories

...