Convert List of String to Array of String in Java

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


 

1. List.toArray()

We can use toArray(T[]) method to copy the list 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.

 

Download   Run Code

Output:

[NYC, New Delhi]

 

2. Java 8

Java 8 provides another simple approach to convert list of string to array of string. Below are the steps:

  1. Convert the specified list of string to a sequential Stream.
     
  2. Use toArray() method to accumulate elements of the stream into a new string array.
     

 

Download   Run Code

Output:

[NYC, New Delhi]

 

3. Arrays.copyOf()

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

 

Download   Run Code

Output:

[NYC, New Delhi]

 

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.

 

Download   Run Code

Output:

[NYC, New Delhi]

 

5. Naive

This post is incomplete without re-inventing the wheels. Naive approach is to use regular for loop to iterate over the list of string and simply copy elements from list to string array.

 

Download   Run Code

Output:

[NYC, New Delhi]

 
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