This post will discuss how to convert an array to a list using plain Java, Guava, and Apache Commons Collections.

There are two general-purpose list implementations in Java — ArrayList and LinkedList. This post will use ArrayList, which offers constant-time positional access and is just plain fast.

1. Naive solution

A naive solution is to create an empty list and push every element of the specified array into the list.

Download  Run Code

Output:

[A, B, C, D]

2. Using Arrays.asList() method

Arrays.asList() returns a fixed-size list backed by the specified array. Since an array cannot be structurally modified, the list will throw an UnsupportedOperationException if we try to add or remove elements from it.

Download  Run Code

Output:

[A, B, C, D]

 
If we need a list that can expand or shrink, we can use:

3. Using Collections.addAll() method

We can use Collections.addAll() to add all elements of the specified array to the specified list, as shown below:

Download  Run Code

We can also use CollectionUtils.addAll() provided by Apache Commons Collections that works in a similar way as Collections.addAll().

4. Using Java 8

We can use Java 8 Stream to convert an array to a list. We first convert the specified array to a sequential Stream and then use a collector to accumulate the input elements into a new List.

Download  Run Code

Output:

[A, B, C, D]

 

Collectors.toList() doesn’t guarantee the type of the list returned. We can use Collectors.toCollection() instead where we can specify the desired Collection. For example,

Download  Run Code

5. Using Guava Library

We can also use Guava API to convert an array to a list.

1. Lists.newArrayList() creates a mutable ArrayList instance containing the given elements. We should use this method to add or remove elements later, or some of the elements can be null.

Download  Run Code

 
2. Guava also provides several simple, easy-to-use immutable versions of List. We can use ImmutableList.copyOf or ImmutableList.of() that returns an immutable list containing the elements of the specified array. These should be preferred where mutability is not required.

Download  Run Code

That’s all about converting an array to a List in Java.