How to convert a List to Array in Java? Example Tutorial

There is no easy way to convert an array to a list in Java, but you can easily convert a list into an array by calling the toArray() method, which List inherits from the Collection interface. If you solely rely on core JDK, then the only way to convert an array to a list is by looping over the array and populating the list one element at a time. But if you can use open source libraries like Google Guava or Apache Commons lang then there are many utility classes to convert list to array and vice-versa, as shown in this tutorial. If you are working on a Java application, you will often need to convert between list and array. 

A list is nothing but a dynamic array that knows how to resize itself when it gets full or gets close to full. List uses load factor to decide when to re-size, the default value of its is 0.75. When they re-size, the list usually doubles their slots e.g. goes from 16 to 32, etc. 

You can find these nifty details in their implementation classes e.g. ArrayList is one of the popular lists in Java which provides order and random access. 

If you want to truly master the Java Collection framework, then you must read the Java Generics and Collection book, written by Maurice Naftaline, and one of the must-read books to become an expert on the Java Collections framework.



Array to List in Java - Example 

You can use advanced for loop or classical for loop to loop over the array and add each object into a list using add() method, this is not a bad approach and you can easily write your own utility method say ArrayUtils.toList() to encapsulate the logic. 

Though you need to be aware to provide several overloaded methods for different types of array e.g. byte[], int[], short[], long[], float[], double[], char[], boolean[] and even object[]

This is cumbersome and that's why it's better to use a common utility library like Guava or Apache commons, which provides these kinds of handy methods right from the box.

Here is how you convert an int array to a List of integers in Java :
 public static List<Integer> toIntegerList(int[] intArray) {
        List<Integer> result = new ArrayList<>(intArray.length);

        for (int i : intArray) {
            result.add(i);
        }

        return result;
    }
Similarly, you need to write other list conversion methods to convert an array of boolean, byte, short, char, long, float, double, or object into the corresponding List in Java.



List to Array in Java - Example

Converting a list to an array is a cakewalk, all you need to do is call the toArray() method to get all items of a list inside an array. This method is overloaded too, the one which doesn't take any parameter returns an Object[] but if you want an array of a particular type, you can use toArray(T[]) which returns all elements of the array with the type you specified. 

It also returns elements in the order they are stored in a list. If the array is not big enough to store all elements another array with sufficient size is created and returned. 

Just remember that you cannot convert List to a primitive array with this method, the only way to do this is iterating over List and converting Integer to int using auto-boxing and storing them into an array.

Here is one example of converting a List of String to an array of String in Java :
List<String> movies = Arrays.asList("Captain America", "Avatar", "Harry Potter");
String[] arrayOfMovies = new String[movies.size()];
movies.toArray(arrayOfMovies);

System.out.println("list of String : " + movies);
System.out.println("array of String : " + Arrays.toString(arrayOfMovies));

Output :
list of String : [Captain America, Avatar, Harry Potter]
array of String : [Captain America, Avatar, Harry Potter]

You can see that array also contains the String in exactly the same order they were in List.

How to convert array to list in Java and vice-versa


Java Program to convert list to array and vice-versa

Here is our sample program to demonstrate how to convert list to array and array to list easily in Java without using any third-party library like Apache Commons Collections or Google Guava.

package dto;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Java program to convert a list to array and vice-versa.
 * 
 * @author WINDOWS 8
 *
 */
public class ListToArrayDemo {

    public static void main(String args[]) {

        // let's create a list first
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
        System.out.println("list : " + numbers);

        // let's first see how easy it is to convert a list to array
        // just call Collection.toArray() method

        // You must pass an Integer[], int[] will not work
        int[] ints = new int[numbers.size()];
        // numbers.toArray(ints); // compile time error expecting Integer[],
        // got
        // int[]

        Integer[] integers = new Integer[numbers.size()];
        numbers.toArray(integers);

        System.out.println("array converted from list : "
                + Arrays.toString(integers));

        // now let's convert an array to a list in Java
        String[] languages = { "Java", "Perl", "Lisp", "JavaScript", "Python" };

        System.out.println("array : " + Arrays.toString(languages));

        List<String> fromArray = new ArrayList<>(languages.length);

        for (String str : languages) {
            fromArray.add(str);
        }

        System.out.println("array to list : " + fromArray);
        
        
        // You can also create utility methods to convert array to list
        // but you need to create total of 9 method, much like various
        // println() method, one for each primitive type and one for
        // all kind of object[]. I have created two of them to
        // show you how to create them, let's see how to use them
        // now.
        
        List<String> names = toList(new String[]{"John", "Mohan", "Mary"});
        System.out.println("list from array in Java : " + names);
        
        List<Integer> primes = toIntegerList(new int[]{2, 3, 5, 7});
        System.out.println("list of Integer from an array of int : " + primes);
    }

    /*
     * Static utility method to convert int[] to List<Integer>
     */
    public static List<Integer> toIntegerList(int[] intArray) {
        List<Integer> result = new ArrayList<>(intArray.length);

        for (int i : intArray) {
            result.add(i);
        }

        return result;
    }

    /*
     * Static utility method to convert T[] to List<T> You can use this method
     * to convert any object[] to List<object.
     */
    public static <T> List<T> toList(T[] tArray) {
        List<T> result = new ArrayList<>(tArray.length);

        for (T object : tArray) {
            result.add(object);
        }

        return result;
    }

}

Output :
list : [1, 2, 3, 4, 5, 6, 7]
array converted from list : [1, 2, 3, 4, 5, 6, 7]
array : [Java, Perl, Lisp, JavaScript, Python]
array to list : [Java, Perl, Lisp, JavaScript, Python]
list from array in Java : [John, Mohan, Mary]
list of Integer from an array of int : [2, 3, 5, 7]


That's all about how to convert a list to array and vice-versa in Java. Yes, there is no direct utility method e.g. toList(array) in JDK API to convert an array to a list but it's not difficult to write one, the only problem is that you need to write 9 overloaded methods to convert a list of 8 primitive types and one object array. 

The good thing is, converting a list to an array is relatively easy with the help of the Collection.toArray() method. Just remember to provide the correct type of array as autoboxing doesn't work with the array. 

If you like this tutorial and wants to learn more about the List interface from the Java Collection framework, you can also check out the following tutorials :
  • How to shuffle elements of a list in Java? [example]
  • How to sort a List in Java? [solution]
  • How to iterate over a list in Java? [solution]
  • What is the difference between List and Set in Java? [answer]
  • How to convert Map to List in Java? [answer]
  • How to create and initialize a List in one line? [answer]
  • How to convert List to Set in Java? [example]
So if you want to convert a List of Integers into an array, make sure you provide an array of integers like new Integer[], an array of primitive int will not work e.g. new int[] will give a compile-time error.

Now is the quiz time, can you pass an array to a method a which is expecting a List in Java?

2 comments:

  1. Hi Javin. I would like to point out that unlike HashMap, ArrayList doesn't has load factor. When new item(s) are added to an ArrayList, the capacity is checked. If the internal array is full, it will grow by 50% or the size that can hold all the new items.

    ReplyDelete
    Replies
    1. @Clarence, Yes you are correct. ArrayList grow automatically using ensureCapacity() method. They don't have load factor. You are also correct that they increased by 50% of the size that can hold all the new elements, finally elements are copied from old array to new array using Arrays.copyOf() method. Thanks for you input, much appreciated.

      Delete

Feel free to comment, ask questions if you have any doubt.