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

ID : 10394

viewed : 9

Tags : javajava

Top 5 Answer for java - How to convert Set<String> to String[]?

vote vote

98

Use the Set#toArray(IntFunction<T[]>) method taking an IntFunction as generator.

String[] GPXFILES1 = myset.toArray(String[]::new); 

If you're not on Java 11 yet, then use the Set#toArray(T[]) method taking a typed array argument of the same size.

String[] GPXFILES1 = myset.toArray(new String[myset.size()]); 

While still not on Java 11, and you can't guarantee that myset is unmodifiable at the moment of conversion to array, then better specify an empty typed array.

String[] GPXFILES1 = myset.toArray(new String[0]); 
vote vote

81

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.

vote vote

74

Use toArray(T[] a) method:

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

63

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

vote vote

54

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)

Top 3 video Explaining java - How to convert Set<String> to String[]?

Related QUESTION?