There are multiple ways to convert an array to a list in Java. In this article, you will learn about different ways of converting an array to a List
in Java.
Convert an array to a list using a loop
Let us start with a simple example that shows how to convert a primitive array int[]
to a List<Integer>
by using a loop:
int[] years = {2015, 2016, 2017, 2018, 2019, 2020};
// convert array to list
List<Integer> list = new ArrayList<>();
for (int y : years) {
list.add(y);
}
// print list elements
for (Integer elem: list) {
System.out.println(elem);
}
The above code will print the following on the console:
2015
2016
2017
2018
2019
2020
Convert an array to a list using Arrays.asList()
For string or object (non-primitive) arrays, you can use the Arrays.asList()
method to easily convert an array to a list. Here is an example of a string array to list conversion:
String[] names = {"Atta", "John", "Emma", "Tom"};
// convert array to list
List<String> list = Arrays.asList(names);
// print list elements
System.out.println(list);
You should see the following output:
[Atta, John, Emma, Tom]
Convert an array to a list using Java 8 Stream
In Java 8+, you can use the Stream API to convert an array to a list, as shown below:
int[] years = {2015, 2016, 2017, 2018, 2019, 2020};
// convert array to list
List<Integer> list = Arrays.stream(years).boxed().collect(Collectors.toList());
// print list elements
list.forEach(System.out::println);
Here is the output:
2015
2016
2017
2018
2019
2020
Java 8 Stream API can also be used for non-primitive arrays:
String[] names = {"Atta", "John", "Emma", "Tom"};
// convert array to list
List<String> list = Arrays.stream(names).collect(Collectors.toList());
Convert an array to a list using List.of()
If you are using Java 9 or higher, you can use the List.of()
method as well for an array to a list conversion:
String[] names = {"Atta", "John", "Emma", "Tom"};
// convert array to list
List<String> list = List.of(names);
// print list elements
System.out.println(list);
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.