Convert Object array to String array in Java

In this post, we will see how to convert Object array to String array in Java.


 

To convert Object array of same type as String:

 

1. 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, Washington DC, New Delhi]

 

2. Arrays.copyOf()

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

 

Download   Run Code

Output:

[NYC, Washington DC, New Delhi]

 

3. List.toArray()

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

 

Download   Run Code

Output:

[NYC, Washington DC, New Delhi]

 

4. Java 8

In Java 8, we can use Stream API to easily convert object array to string array. The idea is to first convert the specified object array to a sequential Stream and then use toArray() method to accumulate the elements of the stream 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

To convert object array of other types than string, one approach is to use 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. Java 8

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

 

Download   Run Code

Output:

[1, 2, 3, 4, 5]

 

 
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