How to Convert Array to ArrayList in Java

In the post How to Convert ArrayList to Array in Java we have already seen different ways of doing that. This post is about the other way round how to convert array to ArrayList in Java.

Options for converting array to ArrayList in Java

  1. Using Arrays.asList() method
  2. Using Collections.addAll() method.
  3. Java 8 on wards you can use Stream API for converting array to ArrayList in Java.
  4. Doing it manually without using any API methods.

Using Arrays.asList() method

Using Arrays.asList() method you can convert array to ArrayList. The returned list by this method is backed by the array, thus any change in the List will be reflected in array too.

Output

As you can see from the output when an element at index 1 is changed in the ArrayList that change is reflected to the array too.

Another drawback of this method is that retuned list is fixed you can’t add or remove element to the returned List. Any attempt to add or remove elements will throw java.lang.UnsupportedOperationException.
Example code

Output

If you need to modify the list you get by converting array to ArrayList then you should create a new ArrayList using the returned list.
Example code

Output

As you can see from the output by creating a new ArrayList you can structurally modify it and now changes are not reflected to the array too.

Using Collections.addAll() method

You can also use Collections.addAll() method to convert array to ArrayList in Java. You need to pass both List and array as arguments to this method.

Example code

Output

Java Stream API’s collect() method

Java 8 on wards you can also use Java Stream API for converting array to ArrayList in Java.

Output

Without using any API method

You can convert array to ArrayList by writing your own logic too rather than using any API method. It required just a simple for loop on which you need to add iterated element of array to ArrayList.

Output

That’s all for the topic How to Convert Array to ArrayList in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.