This article illustrates How to convert between an Array and a List in Java. The examples it covers include plain Java, Guava Library and Apache Commons Collections library.
Tutorial Contents
Convert Array to List
We will see examples of converting an array into a list.
Using Plain Java
The Java provides Arrays
class that contains various static utility methods for arrays. We can use Arrays.asList
method to covert array into list.
Integer[] integerArray = new Integer[]{98, 99, 100};
List<Integer> integerList = Arrays.asList(integerArray);
Code language: Java (java)
However, it is important to note that, the list will refer to the same elements as that from arrays. Thus, a list generated using Arrays#asList
is always of a fixed size.
In order to generate a normal list, which is dynamic in length we can use ArrayList
constructor. For example refer to next
Integer[] integerArray = new Integer[]{98, 99, 100}
List<Integer> integerList = new ArrayList<>(Arrays.asList(integerArray));
Code language: Java (java)
Using Apache Commons Collections Library
We can also use Apache Commons Collections Library to convert an array into a list or append array elements to a list.
Integer[] integerArray = new Integer[]{98, 99, 100};
List<Integer> integerList = new ArrayList<>();
CollectionUtils.addAll(integerList, integerArray);
Code language: Java (java)
Using Guava Library
Similarly, we can use Guava Library to do create a list from an array.
Integer[] integerArray = new Integer[]{98, 99, 100};
List<Integer> integerList = Lists.newArrayList(integerArray);
Code language: Java (java)
The list we get is a completely new ArrayList
having copy of array elements.
Convert List to Array
So far, we have seen various ways to convert an array to a list. In this section we will see how to convert a List into an array.
Using Plain Java
We can convert a list to array by using toArray
method on the list class. However, by default the method returns an object array (Object[]
).
List<Integer> integerList = List.of(50, 51, 52);
Integer[] integerArray = integerList.toArray(new Integer[0]);
Code language: Java (java)
In order to create an array of integers, we have passed an empty array to the method.
Using Guava Library
The guava library also provides a way to create and array from a List.
List<Integer> integerList = List.of(50, 51, 52);
int[] integerArray = Ints.toArray(integerList);
Code language: Java (java)
Summary
In this tutorial we covered different ways of converting between a list and an array in Java. The Java API, Guava API and Apache Commons Collections API provide very easy ways for these conversions. For more Java Tutorials, please visit Java Tutorials.