Convert a List to a Set in Java

Java 8Object Oriented ProgrammingProgramming

In order to convert a List to a Set in Java, we can create an ArrayList and pass the List as an argument in the parameterized constructor of an HashSet. This can be done as follows −

List l = new ArrayList();
Set s = new HashSet(l);

Let us see a program to convert a list to a set in Java −

Example

 Live Demo

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
public class Example {
   public static void main(String[] args) {
      List l = new ArrayList();
      l.add("Good");
      l.add("Morning");
      l.add("Morning");
      Set s = new HashSet(l);
      System.out.println(s);
   }
}

Output

[Morning, Good]
raja
Published on 08-Jan-2019 12:39:34
Advertisements