Convert set to an array in Java
Description
The following code shows how to convert a set to an array.
Example
/*from ww w . j a va2 s. c om*/
import java.util.Arrays;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class Main {
public static void main(String[] argv) {
Set<String> set = new TreeSet<String>();
set.add("b");
set.add("c");
set.add("a");
Iterator it = set.iterator();
while (it.hasNext()) {
Object element = it.next();
System.out.println(element);
}
// Create an array containing the elements in a set
String[] array = (String[]) set.toArray(new String[set.size()]);
Arrays.toString(array);
}
}
The code above generates the following result.