Java how to convert ArrayList to Array Example

By | 2017-12-10T14:04:44+00:00 December 10th, 2017|java8|0 Comments

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 🙂

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment