How Convert an Array to a List in Java
In this tutorial, we will learn how to convert an Array to a List in Java. To convert an array to a list we have three methods
- By adding each element of the array to List explicitly.
- By using
Arrays.asList()
method.
- By using
Collections.addAll()
method
Example: Creating a List from an Array by adding each element to a List from an Array.
In this program, we will iterate an array and add each element to an array. This is a very traditional way and we need to traverse a whole array to add elements into list.
import java.util.*;
public class StudyTonight
{
public static void main(String[] args)
{
List<String> courses= new ArrayList<String>();
String array[] = {"Bangalore","Mumbai","Delhi","Noida"};
for(int i =0;i<array.length;i++)
{
courses.add(array[i]);
}
for(String course: courses)
{
System.out.println(course);
}
}
}
Bangalore
Mumbai
Delhi
Noida
Example: Creating a List from an Array using Arrays.asList()
method.
In the given program we are using the asList()
method from an Arrays
class which receives an array and converts it to List. This method each more efficient than the above example and no need to traverse a whole array.
import java.util.*;
public class StudyTonight
{
public static void main(String[] args)
{
String courses[]={"Bangalore","Mumbai","Delhi","Noida"};
List<String> courseList= new ArrayList<String>(Arrays.asList(courses));
for (String course: courseList)
{
System.out.println(course);
}
}
}
Bangalore
Mumbai
Delhi
Noida
Example: Creating a List from an Array using Collections.addAll()
method.
In this program, we are using the addAll()
method from a Collections
class and this method accept two parameters i.e. list and array and converts that array to list.
import java.util.*;
public class StudyTonight
{
public static void main(String[] args)
{
String array[]={"Bangalore","Mumbai","Delhi","Noida"};
List<String> courses= new ArrayList<String>();
Collections.addAll(courses, array);
for (String course: courses)
{
System.out.println(course);
}
}
}
Bangalore
Mumbai
Delhi
Noida
Conclusion: We can convert Array to List using three methods by adding each element of the array to List explicitly, by using Arrays.asList()
method and by using Collections.addAll()
method. Here the first method is very intuitive and easy but for that, we need to traverse a whole array.