Java – Convert List to Array
This tutorial shows several ways to convert a List to Array in Java.
1- toArray()
List provides a utility method called toArray() which accepts an empty array and populates it with the elements of the array list.
1 2 3 4 5 6 7 | public static String[] convertListToArrayUsingToArray(List<String> names) { String[] namesArr = new String[names.size()]; namesArr = names.toArray(namesArr); return namesArr; } |
In the above example, we initialize an array with the same number of elements as the input list, then we populate it using toArray() method.
2- Traditional way
The other way of converting a List to Array is to do it manually through iterating over the elements of the list and filling up an array as the following:
1 2 3 4 5 6 7 8 9 10 | public static String[] convertListToArrayTraditionalWay(List<String> names) { String[] namesArr = new String[names.size()]; for(int i=0 ; i<names.size(); i++) { namesArr[i] = names.get(i); } return namesArr; } |
3- Java 8
With Java 8, you can convert a List to Array in one line using stream() and toArray() utility methods.
1 2 3 4 5 | public static String[] convertListToArrayJava8(List<String> names) { String[] namesArr = names.stream().toArray(String[]::new); return namesArr; } |
In the above example, we convert the names list into a stream using stream() method and then collect the stream into a new array using toArray().