Java – Convert Array to List

This tutorial shows several ways to convert Array to List in Java.

1- Arrays.asList

You can convert an Array to List using Arrays.asList() utility method. This method accepts an array as input and returns a list as output.

The limitation of using this method is that it returns a fixed size list.

You can just read and overwrite its elements, however if you try to add/remove elements from the returned list you get UnsupportedOperationException.

It’s worth to mention that modifying the elements of the list affects the original array.

In short, this method should only be used for generating a read-only list.

1.1- Generate a modifiable list using Arrays.asList()

In order to support adding/removing elements from the generated list when using Arrays.asList(), you can initialize a completely independent list out of its result as the following:

2- Java 8

With Java 8, you can convert an Array to List in one line using Arrays.stream() and Collectors.toList() utility methods.

Arrays.stream() converts the array into a stream and the stream is then collected as a list using Collectors.toList().

The default type of returned list is ArrayList, in order to decide what type of list to generate use:

3- Traditional way

You can also do the conversion manually through iterating over the elements of the Array and filling up an ArrayList.

 

husseinterek

Founder of programmergate.com, I have a passion in software engineering and everything related to java environment.

You may also like...

Leave a Reply

avatar