1. Introduction
In this post we will see how to convert List<E> to array in 4 different ways. The following methods acts as a bridge between arrays and collections.
2. How to convert List to array?
The 4 ways to convert the List to arrays are as follows:
- Using List interface’s toArray(T[]) method,
- For loop on array
- Stream API
- Google guava library
2.1 Using List interface’s toArray(T[]) method.
Let us say that List<E> consist of Object, more specifically String objects. So now we will try to convert List<String> to String[]. We will use toArray(T[]) method.
toArray method signature.
<T> T[] toArray(T[] a)
List<String> names = Arrays.asList("John", "Jane", "Robb", "Emily"); String[] str = names.toArray(new String[names.size()]); Assert.assertTrue(Arrays.asList(str).equals(names));
2.2 Pull mechanism to array
Second, let’s assume that we have a List<Integer> that we want to convert to int[].
List<Integer> numbers = Arrays.asList(3, 65, 7, 6, 324, 23); int[] arr = new int[numbers.size()]; for (int i = 0; i < numbers.size(); i++) { arr[i] = numbers.get(i).intValue(); // No autoboxing. }
2.3 Stream API
Stream API was added in Java 8 to support sequential and parallel aggregate operations. This operations can be done declaratively and hence code looks more readable.
List<Integer> numbers = Arrays.asList(3, 65, 7, 6, 324, 23); int[] arr = numbers.stream().mapToInt(Integer::intValue).toArray();
2.4 Using Google Guava library.
We can use Ints class’s static method toArray to convert List<Integer> to int[].
List<Integer> numbers = Arrays.asList(3, 65, 7, 6, 324, 23); int[] arr = Ints.toArray(numbers);
3. Conclusion
In this article, we saw few different ways to convert List to array. This article determines how to establish a bridge between Collection and an array.