Java – Convert List to Array

This tutorial shows several ways to convert a List to Array in Java.

1- toArray()

List provides a utility method called toArray() which accepts an empty array and populates it with the elements of the array list.

In the above example, we initialize an array with the same number of elements as the input list, then we populate it using toArray() method.

2- Traditional way

The other way of converting a List to Array is to do it manually through iterating over the elements of the list and filling up an array as the following:

3- Java 8

With Java 8, you can convert a List to Array in one line using stream() and toArray() utility methods.

In the above example, we convert the names list into a stream using stream() method and then collect the stream into a new array using toArray().

husseinterek

Founder of programmergate.com, I have a passion in software engineering and everything related to java environment.

You may also like...

Leave a Reply

avatar