Java Program to Convert List (ArrayList) to Array and Vice-Versa

In this program, you’ll learn to convert a list to an array using toArray() and array to list using asList() in Java.

Example 1: Convert list to array

  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. import java.util.List;
  4. public class ListArray {
  5. public static void main(String[] args) {
  6. List<String> list = new ArrayList<String>();
  7. list.add("a");
  8. list.add("b");
  9. String[] array = new String[list.size()];
  10. list.toArray(array);
  11. System.out.println(Arrays.toString(array));
  12. }
  13. }

When you run the program, the output will be:

[a, b]

In the above program, we’ve an list of strings list. To convert the list to an array, first we created a string array named array with size equals to list.size().

Then, we simply used list’s toArray() method to convert the list items to array items.


Example 2: Convert Array to list

  1. import java.util.Arrays;
  2. import java.util.List;
  3. public class ArrayToList {
  4. public static void main(String[] args) {
  5. String[] array = {"a", "b"};
  6. List<String> list = Arrays.asList(array);
  7. System.out.println(list);
  8. }
  9. }

When you run the program, the output will be:

[a, b]

In the above program, we’ve an array of strings array. To convert the array to a list, we used Arrays‘s asList() method and stored it in the list, list.