How do I Convert Array to List
Published May 20, 2022As Java programmers, we often have to convert arrays to lists, especially when working with a list of items. In this post, we will get started with various ways to convert an array into a list in Java.
3 ways to convert an array to a list
You can use three methods to convert an array to a list. These ways include:
? Creating an empty list and adding elements
? Using Arrays.asList() method
? Using new ArrayList<>(Arrays.asList(arr))
Method 1: Creating an empty list and then adding elements
This method is the simplest of the three, and most developers see it as very trivial and obvious. To use it, all you have to do is follow three simple steps:
? Step 1: First of all, create an empty list
? Step 2: Then, iterate through the array of elements.
? Step 3: Finally, add these elements to your list.
Let's see how these three steps are implemented in the example below:
example
In this example, we are going to create an empty list and add elements
import java.util.ArrayList; import java.util.List; public class Create_List_add_arrays { public static void main(String[] args) { String[] OurArray = new String[] { "123", "456", "789" }; List<String> ourList = new ArrayList<>(); for (int i=0; i<OurArray.length; i++){ ourList.add(OurArray[i]); } System.out.println (ourList); } } |
Output
[123, 456, 789]
Method 2: Using Arrays.asList() method
In this method, we are going to use Arrays.asList (arr) is a built-in method provided by Arrays to convert an array to a list.
Let's take a look at the example below of how this built-in method is implemented:
Example
package Using_Arrays; import java.util.Arrays; import java.util.List; public class using_method { public static void main(String[] args) { String[] OurArray = new String[] { "100", "200", "300" }; List<String> OurList = Arrays.asList(OurArray); System.out.println(OurList);
} } |
Output:
[100, 200, 300]
This method works by creating a fixed-size list which implies that you will not be able to add more elements.
Method 3: Using new ArrayList<>(Arrays.asList(arr))
With this method, we simply use the new arrayList<>(Arrays.asList(integers)); to convert our array to a list. The main advantage of this method over the previous method is that the created array allows the user to add more elements to a list.
Let's look at the example below:
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ArrayList_methods { public static void main(String[] args) { String[] ourArray = new String[] { "100", "200", "300" }; List<String> ourList = new ArrayList<>(Arrays.asList(ourArray)); System.out.println("Our Array: " + ourList); ourList.add("400"); System.out.println("We add a new element: " + ourList ); } } |
Output
Our Array: [100, 200, 300]
We add a new element: [100, 200, 300, 400]
KeyWords: How to convert Array to a List , Java Collections
Article Contributed By :
|
|
|
|
310 Views |