0 votes
1 view
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)

hSet.add(x);

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

for (String x : hSet)

System.out.println(x);

}

}

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

[string].addAll([list]);

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

...