How to Convert an Array to a List in Java
- Create an Empty List and Add All the Elements
-
Use
Arrays.asList()
to Convert an Array to a List in Java -
Use
new ArrayList<>(Arrays.asList(arr))
to Convert an Array to a List in Java
This tutorial discusses three methods to convert an array to a list in Java.
Create an Empty List and Add All the Elements
It is a very trivial and obvious method. We can create an empty list, loop through all the elements in the array, and add them to the list.
The below example illustrates this:
import java.util.*;
import java.util.stream.*;
public class MyClass {
public static void main(String args[]) {
String[] myArray = new String[] {"1", "2", "3"};
List<String> myList = new ArrayList<>();
for (int i = 0; i < myArray.length; i++) {
myList.add(myArray[i]);
}
System.out.println(myList);
}
}
Output:
> [1, 2, 3]
Use Arrays.asList()
to Convert an Array to a List in Java
We can use the built-in method provided by Arrays
class to convert an array to a list - Arrays.asList(arr)
. Make sure to import java.util.*
in your code.
The below example illustrates this.
import java.util.*;
public class MyClass {
public static void main(String args[]) {
String[] myArray = new String[] {"1", "2", "3"};
List<String> myList = Arrays.asList(myArray);
System.out.println(myList);
}
}
Output:
> [1, 2, 3]
However, this method results in a fixed-size list, and we can not add more elements to it.
import java.util.*;
public class MyClass {
public static void main(String args[]) {
String[] myArray = new String[] {"1", "2", "3"};
List<String> myList = Arrays.asList(myArray);
myList.add("4");
}
}
Output:
> Exception in thread "main" java.lang.UnsupportedOperationException
at java.base/java.util.AbstractList.add(AbstractList.java:153)
at java.base/java.util.AbstractList.add(AbstractList.java:111)
at MyClass.main(MyClass.java:6)
Use new ArrayList<>(Arrays.asList(arr))
to Convert an Array to a List in Java
This method, new ArrayList<>(Arrays.asList(integers));
allows you to convert an array to a list, and add you can also add additional elements to the resulting list. Use the below example illustrates this:
import java.util.*;
public class MyClass {
public static void main(String args[]) {
String[] myArray = new String[] {"1", "2", "3"};
List<String> myList = new ArrayList<>(Arrays.asList(myArray));
System.out.println("After conversion from array to list: " + myList);
myList.add("4");
System.out.println("After adding a new element: " + myList);
}
}
Output:
> After conversion from array to list: [1, 2, 3]
> After adding a new element: [1, 2, 3, 4]
Related Article - Java Array
- How to Concatenate Two Arrays in Java
- How to Convert Byte Array in Hex String in Java
- How to Remove Duplicates From Array in Java
- How to Count Repeated Elements in an Array in Java
- Natural Ordering in Java
- How to Slice an Array in Java