In this tutorial, I am going to show you how to convert Java ArrayList to Array.

Java ArrayList to Array :

We can convert an ArrayList to array in below ways.

Java list.toArray()

list.toArray() returns array of objects (Object[]).


import java.util.ArrayList;

public class ArrayListToArray {

    public static void main(String[] args) {
        ArrayList<String> course = new ArrayList<String>();
        course.add("Java");
        course.add("Spring");
        course.add("Hibernate");
        course.add("Angular");
        course.add("PHP");
        Object[] courseArray = course.toArray();
        System.out.println("courseArray.length = " + courseArray.length);

    }

}

[box type=”success” align=”alignleft” class=”” width=”100%”]

courseArray.length = 5

[/box]

Java list.toArray(T[])

We can define the type of an array while converting like below.


import java.util.ArrayList;

public class ArrayListToArray {

    public static void main(String[] args) {
        ArrayList<String> course = new ArrayList<String>();
        course.add("Java");
        course.add("Spring");
        course.add("Hibernate");
        course.add("Angular");
        course.add("PHP");
        Object[] courseArray = course.toArray(new String[course.size()]);
        System.out.println("courseArray.length = " + courseArray.length);

    }

}

[box type=”success” align=”alignleft” class=”” width=”100%”]

courseArray.length = 5

[/box]

Java 8 ArrayList to Array :


import java.util.ArrayList;

public class ArrayListToArray {

    public static void main(String[] args) {
        ArrayList<String> course = new ArrayList<String>();
        course.add("Java");
        course.add("Spring");
        course.add("Hibernate");
        course.add("Angular");
        course.add("PHP");
        String[] courseArray = course.stream().toArray(String[]::new);
        System.out.println("courseArray.length = " + courseArray.length);

    }

}

[box type=”success” align=”alignleft” class=”” width=”100%”]

courseArray.length = 5

[/box]

Happy Learning 🙂