How to Convert a List to an Array in Java


How can we convert a List to an Array in Java?

Suppose we want to convert the following list into an array.

List<String> list;

1. Using toArray(T[] a)

We can use toArray(T[] a) to convert a list to an array. This function returns an array with the elements in the list. The return array type is that of the input array.

String[] arr = list.toArray(new String[0]);

2. Using Streams (Java 8+) and toArray()

We can also use the Stream API to perform this conversion.

String[] arr = list.stream().toArray(String[]::new);

Let’s modify this into a static utility function.

static <T> T[] toArray(List<T> list, Class<T> cls) {
  if (list == null) return null;
  T[] arr = (T[]) Array.newInstance(cls, list.size());
  list.toArray(arr);
  return arr;
}

3. Using Java 11’s toArray()

In Java 11, we can remove the Stream API syntax.

String[] arr = list.toArray(String[]::new);