This post will discuss how to convert a list to an array in Java.

1. Using List.toArray() method

List interface provides the toArray() method that returns an Object array containing the list elements.

 
The JVM doesn’t know the desired object type, so the toArray() method returns an Object[]. We can pass a typed array to the overloaded toArray(T[] a) method to let JVM know your desired object type.

 
We can also pass an empty array (or array of any size) of the specified type, and JVM will allocate the necessary memory:

2. Using Java 8

In Java 8, we can use Stream to convert a list to an array. The idea is to convert the given list to stream using the List.stream() method and uses the Stream.toArray() method to return an array containing the stream elements. There are two ways to do so:

⮚ Using Streams with method reference

⮚ Using Streams with lambda expression

3. Using Guava Library

⮚ Using FluentIterable class

The FluentIterable is an expanded Iterable API that provides similar functionality as Java 8’s streams library in a slightly different way. The idea is to get a fluent iterable that wraps an iterable list and returns an array containing all its elements in iteration order.

⮚ Using Iterables class

Guava’s Iterables class also provides the toArray() method that copies an iterable’s elements into an array.

That’s all about converting List to array in Java.