Core Java

Java Convert a List to Array And Vice-Versa

Introduction:

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!

Convert Java List to Array:

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:

Let’s try them out:

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:

  • If the passed-in array has enough space, then the elements are stored in the same array and a reference to that array is returned
  • If it has more space than the number of elements, the array is first populated with the list elements and the remaining values are populated as null
  • Or else, if it doesn’t have enough space to store the elements, a new array of the same type and sufficient size is created, filled-in and returned

Convert Java Array to List:

To convert an array to a List in Java, we can opt one of the following approaches:

1. Naive Approach(Iteration):

One easy way is to iterate through all the array elements and add them to a newly created List:

We can use the above generic method to easily convert an array of type T:

2. Arrays.asList():

We can also use the asList() method in the java.util.Arrays class to quickly construct a List:

This method accepts the array as its argument.

3. Collections.addAll():

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:

4. Java 8 Streams:

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:

For an array of primitives, we’ll have something like:

Conclusion:

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.

Be the First to comment.

Leave a Comment

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