How can I convert a TreeSet<String> into a String[]?
String[] cityNamesA = (String[]) cityNames.toArray();
How can I convert a TreeSet<String> into a String[]?
String[] cityNamesA = (String[]) cityNames.toArray();
On
Here's a small application that illustrates tree sets, lists, and arrays, with conversions between them. Hope it helps!
import java.util.*;
public class MyClass {
public static void main(String args[]) {
// Make a tree set
Set<Integer> s = new TreeSet<>();
s.add(8);
s.add(21);
s.add(2);
s.add(3);
System.out.println(s);
// Convert tree set to list
List<Integer> l = new ArrayList<>(s);
System.out.println(l);
// Convert tree set to array
Integer[] a = s.toArray(new Integer[0]);
System.out.println(Arrays.toString(a));
}
}
This program outputs:
[2, 3, 8, 21]
[2, 3, 8, 21]
[2, 3, 8, 21]
Update, it seems you just want to convert a TreeSet to an array, not a list. It works the same for any type of collection, including TreeSet: