Convert a Set into a List in Java

Java 8Object Oriented ProgrammingProgramming

First, create a Set and add elements −

Set<Object> s = new HashSet<Object>();
s.add("P");
s.add(new Date());
s.add(new Long(898999));
s.add("Q");
s.add("R");
s.add(new Integer(1));

Convert the above Set to a List −

List<Object> l = new ArrayList<Object>(s);

The following is an example to convert a set into a list in Java −

Example

 Live Demo

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
public class Demo {
   public static void main(String[] args) {
      Set<Object> s = new HashSet<Object>();
      s.add("P");;
      s.add(new Date());
      s.add(new Long(898999));
      s.add("Q");
      s.add("R");
      s.add(new Integer(1));
      List<Object> l = new ArrayList<Object>(s);
      for (int i = 0; i < l.size(); i++) {
         Object ob = l.get(i);
         System.out.println(ob);
      }
   }
}

Output

P
Q
1
R
Sat Jan 05 07:34:56 UTC 2019
898999
raja
Published on 30-Jan-2019 07:32:50
Advertisements