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
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ListArray {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
String[] array = new String[list.size()];
list.toArray(array);
System.out.println(Arrays.toString(array));
}
}
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
import java.util.Arrays;
import java.util.List;
public class ArrayToList {
public static void main(String[] args) {
String[] array = {"a", "b"};
List<String> list = Arrays.asList(array);
System.out.println(list);
}
}
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.