Convert a Set into a List in Java


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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

180 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements