Convert Set of String to Array of String in Java

In this post, we will see how to convert set of string to array of string in Java.


 

1. Naive

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

Java

Download   Run Code

Output:

[Java, C++]

 

2. Set.toArray()

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

Java

Download   Run Code

Output:

[Java, C++]

 

3. Arrays.copyOf()

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

Java

Download   Run Code

Output:

[Java, C++]

 

4. System.arraycopy()

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.

Java

Download   Run Code

Output:

[Java, C++]

 

5. Java 8

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

Java

Download   Run Code

Output:

[Java, C++]

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz