How to convert ‘ArrayList to String array in Java

Using Collection.toArray method

First way to convert arraylist is to use built-in for every java collection method toArray(T[] ts)

For example:

The toArray()  method without any argument returns Object[].  So you have to pass an array as an argument to use method toArray(T[] ts) . This array will be filled with the data from the list, and returned. You can pass an empty array as well, but you can also pass an array with the desired size.

Important note: Originally the code above used new String[list.size()] . But this blogpost reveals that due to JVM optimizations, using new String[0]  is better.

Using Java 8 stream api

An alternative ways to convert arraylist is to use new Stream API available in Java 8:


Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.