Explore Courses Blog Tutorials Interview Questions
0 votes
in Java by (900 points)

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

1 Answer

0 votes
by (13.2k points)

There are 4 easy ways to do this.

  1. Direct

We simply traverse the list and add elements to the set one by one.

import java.util.*;  

class Test {

 public static void main(String[] args)


 List<String> aList = Arrays.asList("intellipaat", "is","a", "great", "community");

Set<String> hSet = new HashSet<String>();

for (String x : aList)


System.out.println("Created HashSet is");

for (String x : hSet)




  1. Using HashSet Constructor

            HashSet Constructor will accept list as a parameter.

Set<String> [string] = new HashSet<String>( [list]);

  1. Using addAll Method

An easy way is to use addAll method, 

Set<String> [string] = new HashSet<String>();


  1. Using Stream 

This method can be used for Java 8, and is again a very simple method to implement 

Set<String> [string] = [list].stream().collect(Collectors.toSet());

Related questions

0 votes
1 answer
asked Feb 24, 2021 in Java by Jake (7k points)
0 votes
1 answer
0 votes
2 answers
0 votes
1 answer
0 votes
1 answer

Browse Categories