How to convert array to array list
How to convert array to array list
How to Convert an array to ArrayList in java
By Chaitanya Singh | Filed Under: Java Collections
In the last tutorial, you learned how to convert an ArrayList to Array in Java. In this guide, you will learn how to convert an array to ArrayList.
Method 1: Conversion using Arrays.asList()
Syntax:
Example:
In this example, we are using Arrays.asList() method to convert an Array to ArrayList.
In the end of the program, we are printing the elements of the ArrayList, which displays 6 elements, four elements that were added to arraylist from array and 2 new elements that are added using add() method.
Output:
Method 2: Conversion using Collections.addAll() method
Collections.addAll() method adds all the array elements to the specified collection. We can call the Collections.addAll method as shown below. It works just like Arrays.asList() method however, it is much faster. Conversion using Collections.addAll() method gives better performance compared to asList() method.
Example:
Output:
Method 3: Convert Array to ArrayList manually
To read the whole array, we are using arr.length property. The array.length property returns the number of elements in the array. In the following example, since the array contains four elements, this will return 4. Thus we can say that the for loop runs from i=0 to i
In the end, we are displaying ArrayList elements using advanced for loop.
Conversion of Array To ArrayList in Java
Following methods can be used for converting Array To ArrayList:
Method 1: Using Arrays.asList() method
Note that the there is an array parameter and List return value.
What if we add more elements to the converted list?
Since returned List is fixed-size List, we can’t add more element(s). An attempt of adding more elements would cause UnsupportedOperationException.
Consider the following example.
It is therefore recommended to create new ArrayList and pass Arrays.asList(array reference) as an argument to it (i.e. as an constructor argument of ArrayList).
Consider the following example:
Method 2: Using Collections.addAll() method
Note that there is a collection parameter c into which elements to be inserted and array parameter a contains the elements to insert into c.
Return type is boolean type. It returns true if the collection changed as a result of the call.
It throws UnsupportedOperationException if collection c does not support add method and throws IllegalArgumentException if some aspect of a value in elements(or elements of array) prevents it from being added to collection c.
Consider the following example:
Adding null to the list
Note : If the specified collection or specified array is null then it throw NullpointerException.
Adding null to the end of list
How to Convert a Java Array to ArrayList
Introduction
In this tutorial, we’ll be converting an array into a more versatile ArrayList in Java.
Thankfully, the Collections Framework introduced us to many very useful implementations of List s, Set s, and Queue s.
Arrays.asList()
Let’s start off with the simplest form of conversion. The Arrays helper class has a lot of useful methods. The asList() method returns the contents of the array in a List :
new ArrayList<>(Arrays.asList())
This is because the asList() method is backed by the original array.
To avoid these, we’ll apply the features of an ArrayList by passing the returned value of asList() to the constructor:
This results in:
new ArrayList<>(List.of())
Since Java 9, you can skip initializing an array itself and passing it down into the constructor. You can use List.of() and pass individual elements:
This results in:
Collections.addAll()
The Collections class offers a myriad of useful helper methods and amongst them is the addAll() method. It accepts a Collection and a vararg of elements and joins them up.
It’s very versatile and can be used with many collection/vararg flavors. We’re using an ArrayList and an array:
This results in:
Collectors.toList()
If you’re working with streams, rather than regular collections, you can collect the elements of the stream and pack them into a list via toList() :
Running this will yield:
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Collectors.toCollection()
Similarly, you can use the toCollection() method to collect streams into different collections. In our case, we’ll supply the ArrayList::new method reference into it, though you could supply other references as well:
This also results in:
Lists.newArrayList()
Similar to the Arrays.asList() helper class and method, Google’s Guava project introduced us to the Lists helper class. The Lists helper class provides the newArrayList() method:
However, as Java 7 removed the need to explicitly set the type in the diamond operator, this became obsolete.
Conclusion
There are numerous ways to convert an array to an ArrayList in Java. These span from calling helper methods to streaming the array and collecting the elements.
Converting array to list in Java
How do I convert an array to a list in Java?
I used the Arrays.asList() but the behavior (and signature) somehow changed from Java SE 1.4.2 (docs now in archive) to 8 and most snippets I found on the web use the 1.4.2 behaviour.
In many cases it should be easy to detect, but sometimes it can slip unnoticed:
22 Answers 22
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
In your example, it is because you can’t have a List of a primitive type. In other words, List is not possible.
You can, however, have a List using the Integer class that wraps the int primitive. Convert your array to a List with the Arrays.asList utility method.
In Java 8, you can use streams:
Java 16
Java 8 (int array)
Java 8 and below (Integer array)
Need ArrayList and not List?
In case we want a specific implementation of List e.g. ArrayList then we can use toCollection as:
Why list21 cannot be structurally modified?
To be clear list21 can be modified in sense that we can call list21.set(index,element) but this list may not be structurally modified i.e. cannot add or remove elements from the list. You can also check this answer of mine for more explanation.
If we want an immutable list then we can wrap it as:
Another point to note is that the method Collections.unmodifiableList returns an unmodifiable view of the specified list. An unmodifiable view collection is a collection that is unmodifiable and is also a view onto a backing collection. Note that changes to the backing collection might still be possible, and if they occur, they are visible through the unmodifiable view.
We can have a truly immutable list in Java 9 and 10.
Assigning an array to an ArrayList in Java
Is it possible to assign an array to an ArrayList in Java?
4 Answers 4
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Note that you aren’t technically assigning an array to a List (well, you can’t do that), but I think this is the end result you are looking for.
The Arrays class contains an asList method which you can use as follows:
If you are importing or you have an array (of type string) in your code and you have to convert it into arraylist (offcourse string) then use of collections is better. like this:
This is working
Not the answer you’re looking for? Browse other questions tagged java arrays arraylist or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.