In this short article, you will learn about different ways of converting an array to a List in Java.

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

Using Arrays.asList() Method

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]

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());

Using List.of() Method

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 @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Buy me a coffee (cost $3)

Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.