This post will discuss how to convert the object array to a string array in Java.

To convert object array of same type as String

1. 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:

[NYC, Washington DC, New Delhi]

2. 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:

[NYC, Washington DC, New Delhi]

3. Using List.toArray() method

Here we first convert the object array to a list of objects and then use the toArray(T[]) method to dump the list into a newly allocated array of String.

Download  Run Code

Output:

[NYC, Washington DC, New Delhi]

4. Using Java 8

In Java 8, we can use Stream to convert object array to string array easily. The idea is first to convert the specified object array to a sequential Stream and then use the toArray() method to accumulate the stream elements into a new string array.

Download  Run Code

Output:

[NYC, Washington DC, New Delhi]

 

To convert object array of other types than String

1. Naive solution

To convert an object array of other types than string, one approach uses a regular for-loop to iterate over the object array, and for every object, we cast it to string and assign it to the string array.

Download  Run Code

Output:

[1, 2, 3, 4, 5]

2. Using Java 8

This is similar to the Java 8 approach discussed earlier, except here we call the Stream.map() method to convert every object in the stream to their string representation before calling the toArray() method.

Download  Run Code

Output:

[1, 2, 3, 4, 5]

That’s all about converting object array to string array in Java.