Program to convert Set to List in Java

Java 8Object Oriented ProgrammingProgramming

Let’s say the following is our Set with string values −

Set<String> set = new HashSet<String>();
set.add("Laptop");
set.add("Mobile");
set.add("Tablet");
set.add("LCD");
set.add("LED");

Now, let us convert it to List −

List<String> list = new ArrayList<>(set);

Following is the program to convert Set to List in Java −

Example

import java.util.*;
import java.util.stream.*;
public class Demo {
   public static void main(String args[]) {
      Set<String> set = new HashSet<String>();
      set.add("Laptop");
      set.add("Mobile");
      set.add("Tablet");
      set.add("LCD");
      set.add("LED");
      set.add("Desktop");
      System.out.println("Set = " + set);
      List<String> list = new ArrayList<>(set);
      System.out.println("List = " + list);
   }
}

Output

Set = [Laptop, Desktop, Tablet, LED, LCD, Mobile]
List = [Laptop, Desktop, Tablet, LED, LCD, Mobile]
raja
Published on 23-Sep-2019 14:02:50
Advertisements