Converting from a tree set into an Array?

2.8k views Asked by At

How can I convert a TreeSet<String> into a String[]?

String[] cityNamesA = (String[]) cityNames.toArray();
2

There are 2 answers

7
Sean Patrick Floyd On

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:

String[] cityNamesA = cityNames.toArray(new String[cityNames.size()]);
0
Ray Toal 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]