Collections FrameworkJava-Collection-Examples

How to convert a List to a Set

Posted On
Posted By admin

In this blog post ,I will be showing you how you can convert a List to a Set. Consider the following code snippet:


public class ListToSetDemo {

public static void main(String[] args) {
List<Integer> list = Arrays.asList(5,3,11,15,9);

//Method 1
Set<Integer> set = new HashSet<Integer>(list);
System.out.println("Set is "+set);

//method 2
Set<Integer> set2 = new HashSet<Integer>();
set2.addAll(list);
System.out.println("Set is "+set2);

}
}

This code demonstrates two ways to convert a List to a Set.

Method 1

Here, we are creating a new HashSet. We are invoking the constructor that accepts a Collection object. Here, we are passing in the input list to this constructor.

 

Method 2

Here again, we are creating a new HashSet. However, we are using the default constructor. We are then invoking the addAll method and passing in the input list.

 

When you run this code, it will print the following output:

Set is [3, 5, 9, 11, 15]
Set is [3, 5, 9, 11, 15]

Note that the order of the elements in the Set is not the same as in the input List.

 

If you like this post, please do let me know via the comments box below.  You can also connect with me via my Facebook Page or subscribe to my Youtube channel!

Related Post

leave a Comment