This post will discuss how to convert a set of string to a string array in Java.

1. Naive solution

A naive solution is to use a for-each loop to iterate over the given set and simply copy elements from set to string array.

Download  Run Code

Output:

[Java, C++]

2. Using Set.toArray() method

We can use the toArray(T[]) method to copy the set into a newly allocated string array. We can either pass a string array as an argument to the toArray() method or pass an empty string type array. If an empty array is passed, JVM will allocate memory for the string array. Please note that if no argument is passed to toArray(), it will return an Object array.

Download  Run Code

Output:

[Java, C++]

3. Using Arrays.copyOf() method

We can also use Arrays.copyOf() to copy the specified array to an array of the specified type.

Download  Run Code

Output:

[Java, C++]

4. Using System.arraycopy() method

We can use System.arraycopy() that copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array.

Download  Run Code

Output:

[Java, C++]

5. Using Java 8

Java 8 provides another simple approach to convert Set to a string array. First, we convert the specified set of strings to a sequential Stream and then use the toArray() method to accumulate the stream elements into a new string array.

Download  Run Code

Output:

[Java, C++]

That’s all about converting Set of String to an array of Java String.