Collections

Convert List to Array Java Example

Convert List to Array Java example shows how to convert List to array in Java. Example also shows how to convert List to primitive array and convert List to array using Apache Commons library.

How to convert List to Array in Java?

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

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

Output

Note:

If you pass an array whose length is less than that of the List to toArray method, List will still be converted to an array of 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 creation of another array.

How to convert List to Array of primitive type?

Above method works only for the List containing reference objects. If you want to convert List to array of primitive type, you need to loop through the elements of the List and fill the array as given in below example. You can also use Apache commons library.

a) Convert List to primitive array using For loop

Output

b) Convert List to primitive array using Apache Commons library

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

Output

How to convert List to Array using Java 8 Stream?

Output

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

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.