Skip to content

Convert List to Array Java Example

Convert List to array Java example shows how to convert List to an array in Java including a primitive array using for loop, toArray method, Stream, and Apache Commons.

How to convert List to Array in Java?

The List can be converted to an array using the toArray method of the List.

This method returns an array containing all the elements of the argument list in the same sequence. The type of array returned from this method is the same as the argument array.

Output

Note:

If you pass an array smaller than the List to the toArray method, List will still be converted to an array of the correct type, but in that case, a new array will be created by JVM of the same type. It is always suggested to pass an array of the same size to avoid the creation of another array.

How to convert List to an array of primitive types?

The above method works only for the List containing object references. If you want to convert List to an array of primitive types, you need to loop through the elements of the List and fill the array as given in the below example. You can also use the Apache commons library.

a) Using For loop

Output

b) Using Apache Commons library

You can use the toPrimitive method of the ArrayUtils class of the Apache commons library as given below.

Output

How to convert using the Java 8 Stream?

Output

This example is a part of the Java Array tutorial and 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.