In this article, we’ll quickly learn how to convert a Java List (say an ArrayList) to an array and vice-versa. If you wish to learn more about an ArrayList in general, feel free to read our article on Java ArrayLists.
Meanwhile, let’s get going!
Converting a Java List to an array is very simple and straight-forward. We can use one of the two available flavors of the toArray() method:
//Returns an Object-type array Object[] toArray() //Returns an array of type T T[] toArray(T[] array)
Let’s try them out:
List<Integer> list = Arrays.asList(1, 2, 3, 4); Object[] arrayOfObjects = list.toArray(); Integer[] arrayOfIntegers = list.toArray(new Integer[list.size()]);
The toArray(T[] array) method accepts as well as returns an array. The main purpose of passing in an array is to inform the type of an array that’s to be returned:
To convert an array to a List in Java, we can opt one of the following approaches:
One easy way is to iterate through all the array elements and add them to a newly created List:
public <T> List<T> convertArrToList(T[] array) { List<T> list = new ArrayList<>(); for(T element : array) { list.add(element); } return list; }
We can use the above generic method to easily convert an array of type T:
Integer[] arr = {1, 2, 3}; List<Integer> list = c.convertArrToList(arr);
We can also use the asList() method in the java.util.Arrays class to quickly construct a List:
public <T> List<T> convertArrToList(T[] array) { return Arrays.asList(array); }
This method accepts the array as its argument.
As we know, java.util.Collections offer the addAll(Collection c, T… elements) method which adds all the elements to the given collection c.
Since List inherits from the Collection interface, we can use this method to our advantage:
public <T> List<T> convertArrToList(T[] array) { List<T> list = new ArrayList<>(); Collections.addAll(list, array); return list; }
Java 8 onwards, we can first open a stream over a Java array and then collect its elements in a List using Java Stream Collectors:
public <T> List<T> convertArrToList(T[] array) { return Arrays.stream(array).collect(Collectors.toList()); }
For an array of primitives, we’ll have something like:
int[] array = new int[] { 1, 2, 3 }; List<Integer> list = Arrays.stream(array) .boxed() .collect(Collectors.toList());
In this tutorial, we looked at how to convert a Java List to an array. We also covered the other scenario of converting an array to a List in Java.