How to convert List to Array in Java

Last updated on July 9, 2020 by Dan Nanni

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 of 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 of 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()]));

Support Xmodulo

This website is made possible by minimal ads and your gracious donation via PayPal or credit card

Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.

Xmodulo © 2021 ‒ AboutWrite for UsFeed ‒ Powered by DigitalOcean