Tuesday, August 04, 2009

How do I convert Set into List?

Conversion between the collections made pretty easy in Java.

Converting from a Set/List to List/Set can be done by passing the Set/List instance to the constructor of List/Set such as ArrayList/HashSet respectively.

Following line of code performs the conversion (from Set to List):

Set strSet = new HashSet();
strSet.add("one")
.
.
.
strSet.add("xxx");

List strList = new ArrayList(set);

Above List can be converted back to Set using the following line of code:

Set setObject = new HashSetst(strList);

Following is the example program that does the entire same thing we discussed above:
-----
package com.blog.javaexposure.util;

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

public class Set2List {

public static void main(String rags[]) {
// Creating a Set object
Set set = new HashSet();
// Adding elements to the Set object
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");

// Checking the elements in the Set
System.out.println("Elements in the set are:");
for (Object obj : set) {
System.out.println(obj);
}

// Creating a list object
List list = new ArrayList(set);

// Checking the elements in the list
System.out.println("Elements in the list are:");
for (Object obj : list) {
System.out.println(obj);
}
// Removing elements from the set
set.clear();
System.out.println("Number of elements in the set are: "+set.size());

// Converting list to set
set = new HashSet(list);

// Checking the elements in the Set
System.out.println("Elements in the set are:");
for (Object obj : set) {
System.out.println(obj);
}
}
}
-----

1 comment:

È