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:

//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:

  • 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:

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);

2. Arrays.asList():

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.

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:

public <T> List<T> convertArrToList(T[] array) {
    List<T> list = new ArrayList<>();
    Collections.addAll(list, array);
    return list; 
}

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:

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

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.

Published on Java Code Geeks with permission by Shubhra Srivastava, partner at our JCG program. See the original article here: http://www.programmergirl.com/convert-list-array-java/

Opinions expressed by Java Code Geeks contributors are their own.

Shubhra Srivastava

Shubhra is a software professional and founder of ProgrammerGirl. She has a great experience with Java/J2EE technologies and frameworks. She loves the amalgam of programming and coffee :)
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
SOURAV KUNDU
SOURAV KUNDU
5 years ago

Nice article to have all the possible conversion at one place. But maybe you can try explaining how it works internally. It will help to understand more easily.

Back to top button