Thursday, August 06, 2009

Converting an Array to a Set

To my knowledge we do not have any direct methods to convert from an array to a set. this To achieve this, we have to do the conversion process in two steps.
1. Converting an array to List
2. Converting the resulting List to a Set

Following program constructs an array with strings, String array is converted into a List using the asList method available in Arrays. Then the resulting list is converted into a Set.

---
package com.blog.javaexposure.util;

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

public class Array2Set {
public static void main(String rags[]){
// Creating a string array
String[] str = {"One","Two","Three","Four","
Five"};

// Convert array to List
List list = Arrays.asList(str);

System.out.println("Elements in the list are:");
//Checking the elements in the list
for(String s : list){
System.out.println(s);
}

// Convert list to set
Set set = new HashSet(list);

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

No comments:

Post a Comment

È