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.
Did you find this tutorial helpful? Then please be generous and support Xmodulo!