[java] How to convert Set<String> to String[]?

I need to get a String[] out of a Set<String>, but I don't know how to do it. The following fails:

Map<String, ?> myMap = gpxlist.getAll();
Set<String> myset = myMap.keySet();
String[] GPXFILES1 = (String[]) myset.toArray(); // Here it fails.

How can I fix it so that it works?

This question is related to java

The answer is


Use toArray(T[] a) method:

String[] array = set.toArray(new String[0]);

Set<String> stringSet= new HashSet<>();
String[] s = (String[])stringSet.toArray();

In Java 11 we can use Collection.toArray(generator) method. The following code will create a new array of String:

Set<String> set = Set.of("one", "two", "three");
String[] array = set.toArray(String[]::new)

See: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Collection.html#toArray(java.util.function.IntFunction)


I was facing the same situation.

I begin by declaring the structures I need:

Set<String> myKeysInSet = null; String[] myArrayOfString = null;

In my case, I have a JSON object and I need all the keys in this JSON to be stored in an array of strings. Using the GSON library, I use JSON.keySet() to get the keys and move to my Set :

myKeysInSet = json_any.keySet();

With this, I have a Set structure with all the keys, as I needed it. So I just need to the values to my Array of Strings. See the code below:

myArrayOfString = myKeysInSet.toArray(new String[myKeysInSet.size()]);

This was my first answer in StackOverflow. Sorry for any error :D


Guava style:

Set<String> myset = myMap.keySet();
FluentIterable.from(mySet).toArray(String.class);

more info: https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/FluentIterable.html


Java 11

The new default toArray method in Collection interface allows the elements of the collection to be transferred to a newly created array of the desired runtime type. It takes IntFunction<T[]> generator as argument and can be used as:

 String[] array = set.toArray(String[]::new);

There is already a similar method Collection.toArray(T[]) and this addition means we no longer be able to pass null as argument because in that case reference to the method would be ambiguous. But it is still okay since both methods throw a NPE anyways.

Java 8

In Java 8 we can use streams API:

String[] array = set.stream().toArray(String[]::new);

We can also make use of the overloaded version of toArray() which takes IntFunction<A[]> generator as:

String[] array = set.stream().toArray(n -> new String[n]);

The purpose of the generator function here is to take an integer (size of desired array) and produce an array of desired size. I personally prefer the former approach using method reference than the later one using lambda expression.