Convert List to array in Java
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.
1 2 3 |
List<String> list = Arrays.asList("C", "C++", "Java"); Object[] array = list.toArray(); System.out.println(Arrays.toString(array)); |
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.
1 2 3 |
List<String> list = Arrays.asList("C", "C++", "Java"); String[] array = list.toArray(new String[list.size()]); System.out.println(Arrays.toString(array)); |
We can also pass an empty array (or array of any size) of the specified type, and JVM will allocate the necessary memory:
1 2 3 |
List<String> list = Arrays.asList("C", "C++", "Java"); String[] array = list.toArray(new String[0]); System.out.println(Arrays.toString(array)); |
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
1 2 3 |
List<String> list = Arrays.asList("C", "C++", "Java"); String[] array = list.stream().toArray(String[]::new); System.out.println(Arrays.toString(array)); |
⮚ Using Streams with lambda expression
1 2 3 |
List<String> list = Arrays.asList("C", "C++", "Java"); String[] array = list.stream().toArray(n -> new String[n]); System.out.println(Arrays.toString(array)); |
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.
1 2 3 |
List<String> list = Arrays.asList("C", "C++", "Java"); String[] array = FluentIterable.from(list).toArray(String.class); System.out.println(Arrays.toString(array)); |
⮚ Using Iterables
class
Guava’s Iterables
class also provides the toArray()
method that copies an iterable’s elements into an array.
1 2 3 |
List<String> list = Arrays.asList("C", "C++", "Java"); String[] array = Iterables.toArray(list, String.class); System.out.println(Arrays.toString(array)); |
That’s all about converting List to array in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)