Powered by Blogger.

Can i convert Set into List ?

>> Friday, June 10, 2011

Yes.we can convert a Set into List.The List and Set both are interfaces having superclass of Collection interface.

Create an object of HashSet which is implemented a Set Interface.Add the objects to the HashSet using add() method.


Set<String> set = new HashSet<String>();
  set.add("username");
  set.add("password");
  set.add("login");

And same Create an object of ArrayList which is implemented a List Interface.Pass the reference object of Set while creating the ArrayList object.

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



Program to Convert Set to List:

package javabynataraj.collections;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class SetToList {
 
 public static void main(String[] args) {
  //create a set object with some data
  
  Set<String> set = new HashSet<String>();
  set.add("username");
  set.add("password");
  set.add("login");
  System.out.println("1.The Set Objects are:");
  System.out.println(set);
  
  //create a list object
  List<String> list = new ArrayList<String>(set);
  //The converted list from set Object
  System.out.println("2.The List Objects are");
  System.out.println(list);
  System.out.println("3.By iterating the values from list");
  Iterator<String> it = list.iterator();
  while(it.hasNext()){
   System.out.println(it.next());
  }
 }
}


The Output of the above program:



Reference Books:

Java Generics and Collections  Java Collections

Related Posts Plugin for WordPress, Blogger...
© javabynataraj.blogspot.com from 2009 - 2022. All rights reserved.