Convert List to Array in Java

In this post, we will see how to convert list to array in Java.


 

1. List.toArray()

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

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

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

 

2. Java 8

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

1. Streams + method reference

2. Streams + lambda expression

 

3. Guava Library

 

3.1. Using FluentIterable class –

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 iterable list and returns an array containing all of the elements from it in iteration order.

 

3.2. Using Iterables class –

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

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz