Skip to content

Convert ArrayList to String[] array in Java Example

Convert ArrayList<String> to String[] array in Java example shows how to convert ArrayList<String> to String[] array in Java. The example also shows various ways to convert ArrayList of String to String array in Java.

How to convert ArrayList<String> to String[] array in Java?

There are several ways using which you can convert ArrayList<String> to String[] array in Java as given below.

1) Convert ArrayList of String to String array using for loop

Probably the simplest way is to use for loop or enhanced for loop to iterate the ArrayList and add elements one by one to the String array as given below.

Output

2) Convert using the toArray method

You can use toArray method of the ArrayList class to convert the ArrayList of String to String array in Java.

This method returns an array of type T containing all the elements of the List in the sequence returned by List’s iterator. If the specified array is large enough to fit all the List elements, it is returned, otherwise, a new array is created with the type T and size of the List and returned.

Output

It is a good practice to pass an array of the same length as that of the List to toArray method to avoid unnecessary creation of new Array.

Note: toArray method may throw NullPointerException if the argument array is null.

3) Convert using Java 8 Stream

If you are using Java 8, you can use Java stream to convert ArrayList to String array as given below.

Output

This example is a part of the Java ArrayList tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.