Convert List to Array

JavaJavaBeginner
Practice Now

Introduction

In this lab, we will learn how to convert a List to an array in Java. The List is a linear data structure that stores data, while the array is an indexed data structure that stores similar types of data. We will use the toArray() method of the List interface that returns an array of objects.

Create a List

We will create a List of vegetables and print its elements.

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

public class Main {
    public static void main(String[] args) {
        List<String> vegetables = new ArrayList<>();
        vegetables.add("Carrot");
        vegetables.add("Potato");
        vegetables.add("Tomato");
        System.out.println("Vegetables List: " + vegetables);
    }
}

Compile and run the above code using the following command.

javac Main.java && java Main

Convert List to Array

Now we will convert the List to an array using the toArray() method. The toArray() method returns an array of Object elements. So if you want to get another type of array, then pass an object of that type as an argument.

//Conversion List to Array
String[] newArray =  vegetables.toArray(new String[0] );
System.out.println("New Array: " + newArray);
for (int i = 0; i < newArray.length; i++) {
    System.out.println(newArray[i]);
}

Compile and run the above code using the following command.

javac Main.java && java Main

Convert with Stream() Method

If you are using Java 8 or higher version then you can use the stream() method to get a stream of elements and then use method reference syntax to get an array of string type elements from the list.

//Conversion List to Array with Stream Method
String[] newArray =  vegetables.stream().toArray(String[]::new);
System.out.println("New Array: " + newArray);
for (int i = 0; i < newArray.length; i++) {
    System.out.println(newArray[i]);
}

Compile and run the above code using the following command.

javac Main.java && java Main

Convert with Directly Using toArray() Method

If you are using the latest Java versions, then you can get an array from the list without using stream() method and directly use toArray() method.

//Conversion List to Array without using stream() method
String[] newArray =  vegetables.toArray(String[]::new);
System.out.println("New Array: " + newArray);
for (int i = 0; i < newArray.length; i++) {
    System.out.println(newArray[i]);
}

Compile and run the above code using the following command.

javac Main.java && java Main

Summary

In this lab, we learned how to convert a List to an array in Java. We used the toArray() method of the List interface to convert the List to an array. We also learned various methods to convert the List to an array like using stream() method or directly using toArray() method.

Other Java Tutorials you may like