How to convert List to Array in Java

Suppose you are maintaining a list of objects using List (i.e., List<Object>), and want to convert it into an array of objects (i.e., Object[]). How would you convert List to Array in Java?

To do that, you can in general take advantage of List.toArray(), which returns Object[], an array of all the elements in the list.

Here is a code example on converting List to Array with List.toArray().

List<String> strList = new ArrayList<String> ();
strList.add("apple");
strList.add("orange");
strList.add("mango");

String[] strArray = strList.toArray(new String[strList.size()]);

However, one caveat of this approach is that List.toArray() does not work with primitive object types such as int, float, etc.

In order to convert List of primitive types to a corresponding array, you can leverage ArrayUtils.toPrimitive(Object[] array), which converts an array of non-primitive Objects to primitives. ArrayUtils is available in Apache Commons Lang library.

Here is a code example on converting List<Integer> to int[] with ArrayUtils.toPrimitive().

import org.apache.commons.lang.ArrayUtils;

List<Integer> intList;
intList.add(1);
intList.add(5);
intList.add(7);

int[] intArray = ArrayUtils.toPrimitive(intList.toArray(new Integer[intList.size()]));

Subscribe to Xmodulo

Do you want to receive Linux FAQs, detailed tutorials and tips published at Xmodulo? Enter your email address below, and we will deliver our Linux posts straight to your email box, for free. Delivery powered by Google Feedburner.


Support Xmodulo

Did you find this tutorial helpful? Then please be generous and support Xmodulo!

The following two tabs change content below.
Dan Nanni is the founder and also a regular contributor of Xmodulo.com. He is a Linux/FOSS enthusiast who loves to get his hands dirty with his Linux box. He likes to procrastinate when he is supposed to be busy and productive. When he is otherwise free, he likes to watch movies and shop for the coolest gadgets.

One thought on “How to convert List to Array in Java

  1. Your article title is misleading. Your article shows a solution to convert Lists of wrapped primitive values to arrays of same.

    HTH

Leave a comment

Your email address will not be published. Required fields are marked *