Converting a List to an Array in Java

There are multiple ways to convert a list into an array in Java. Here are a few examples that demonstrate how you can easily convert a list to an array in Java:

Example 1

Here's in this example, we have a list of strings, strList. We are converting this list into an array of strings, strArray, by using the strList.toArray(...) method. To determine the size of the array, we use strList.size(), and a new array of strings with the same size is created using new String[strList.size()]. Ultimately, strArray holds the same strings as the original list, offering a concise approach to transform a list of strings into a string array in Java.

// 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()]);

Example 2

Here's another example where we have a List<Integer> named intList containing integers. To convert this list to a primitive int array, we create a new array, intArray, with the same size as intList. Using a loop, each element from the list is copied to the corresponding position in the array. After the loop, intArray holds the same integers as intList, completing the conversion of the list of integers to a primitive int array.

// 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);
}

Example 3

Here's third example where we are using the stream() method to convert the List<Integer> to a stream of integers. Then, we use the mapToInt() method to convert each element of the stream to its primitive int representation. The lambda expression i -> i is essentially an identity function, meaning it returns the element itself. Finally, toArray() is used to collect the elements into an array of primitive int.

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

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

Example 4

In the example below, instead of using a lambda expression, we are using a method reference Integer::intValue. This method reference is equivalent to the lambda expression i -> i.intValue(). It converts each Integer object to its primitive int value. The rest of the process (stream, mapToInt(), toArray()) is the same as in Example 3.

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

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