Wednesday , January 17 2018
Home / java8 / Java how to convert ArrayList to Array Example

Java how to convert ArrayList to Array Example

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

    }

}

courseArray.length = 5

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

    }

}

courseArray.length = 5

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

    }

}

courseArray.length = 5

Happy Learning 🙂

About chandrashekhar

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+ ,

Recommended

Java 8 Array contains a specific value ?

In this tutorials I am going to show you how to check an array contains …

Leave a Reply

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