Java Program to convert a List to a Set

Java 8Object Oriented ProgrammingProgramming

To convert a List to a Set, let us first create a list and add elements:

List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);

Now, let us convert the above list to a set with HashSet:

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

Example

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Demo {
   public static void main(String[] args) {
      List<Integer> list = new ArrayList<Integer>();
      list.add(10);
      list.add(20);
      list.add(30);
      list.add(40);
      list.add(50);
      list.add(20);
      list.add(40);
      list.add(50);
      Set<Integer> set = new HashSet<Integer>(list);
      System.out.println("Set = ");
      for (Object ob : set)
         System.out.println(ob);
   }
}

Output

Set =
50
20
40
10
30
raja
Published on 25-Apr-2019 12:51:33
Advertisements