Java Program to Convert a List to Array and Vice Versa

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Convert the Java List into Array

import java.util.ArrayList;

class Main {
  public static void main(String[] args) {
    ArrayList languages = new ArrayList<>();

    // Add elements in the list
    languages.add("Java");
    languages.add("Python");
    languages.add("JavaScript");
    System.out.println("ArrayList: " + languages);

    // Create a new array of String type
    String[] arr = new String[languages.size()];

    // Convert ArrayList into the string array
    languages.toArray(arr);
    System.out.print("Array: ");
    for(String item:arr) {
      System.out.print(item+", ");
    }
  }
}

Output

List: [Java, Python, JavaScript]
Array: Java, Python, JavaScript,

In the above example, we have created an list named languages. Here, we have used the ArrayList class to implement the List.

Notice the line,

languages.toArray(arr);

Here, the toArray() method converts the list languages into an array. And stores it in the string array arr.

Note: If we don't pass any argument to the toArray() method, the method returns an array of the Object type.


Example 2: Convert Java Array to List

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

class Main {
  public static void main(String[] args) {

    // create an array
    String[] array = {"Java", "Python", "C"};
    System.out.println("Array: " + Arrays.toString(array));

    // convert array to list
    List languages= new ArrayList<>(Arrays.asList(array));

    System.out.println("List: " + languages);

  }
}

Output

Array: [Java, Python, C]
List: [Java, Python, C]

In the above example, we have created an array of String type. Notice the expression,

Arrays.asList(array)

Here, the asList() method of the Arrays class converts the specified array into a list.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges