How to Efficiently Convert a List to an Array in Java?

There are many ways for converting a list into an Array in Java. The following are some of the examples of how you can efficiently convert a list to an array in Java:

List of String Items to String Array


// sample list of string items
List<String> strList = Arrays.asList("Science", "English", "Geography", "Economics", "Computer");
//converting list to string array 
String [] strArray = strList.toArray(new String[strList.size()]);

List of Integer Items to int Array

Below Java 8:


// sample list of int items
List<Integer> intList = Arrays.asList(1, 2, 3, 4, 6, 7, 8, 9);
// converting list of integers to int array 
int[] intArray = new int[intList.size()];
for (int i = 0; i < intArray.length; i++) {
	intArray[i] = intList.get(i);
}

In Java 8 and above:


// sample list of int items
List<Integer> intList = Arrays.asList(1, 2, 3, 4, 6, 7, 8, 9);

// example 1
int[] intArray1 = intList.stream().mapToInt(i->i).toArray();

// example 2
int[] intArray2 = intList.stream().mapToInt(Integer::intValue).toArray();