Convert an Array to a List in Java

In this post, we will see 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. In this post, we’ll be using ArrayList, which offers constant-time positional access and is just plain fast.

 

1. Naive

Naive solution would be to create an empty list and push every element of the specified array into the list.

Java

Download   Run Code

Output:

[A, B, C, D]

 

2. Arrays.asList() –

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.

Java

Download   Run Code

Output:

[A, B, C, D]

If we need a List that can expand or shrink, we can use –

 

3. Collections.addAll() –

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 similar way as Collections.addAll().

 

4. Java 8 –

We can use Java 8 Stream API 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.

Java8

Download   Run Code

Output:

[A, B, C, D]

Collectors.toList() doesn’t guarantees on 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. Guava –

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

1. Lists.newArrayList() creates a mutable ArrayList instance containing the given elements. This method should be used if you need 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

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz