How to Convert an Array to List in Java?

Though an array is an object in Java, it doesn’t have the required methods to convert it to a List object, it just contains the basic methods that it derived from the Object class. But if you want to convert an array to List, we have other alternatives.

Using Arrays.asList(Object[])

Arrays.asList method can take an object array and return it as a List object. However, you should be careful when you are using asList method which I explained in this post in detail. Basically, you cannot edit the returned list.

package com.techstackjournal;

import java.util.Arrays;
import java.util.List;

public class ArrayToList {

	public static void main(String[] args) {
		
		String[] arr = {"Alpha", "Beta", "Gamma"};
	
		List list = Arrays.asList(arr);
		
		
		for (Object object : list) {
			System.out.println(object);
		}
		
	}

}

Using Collections.addAll(Collection c, T… elements)

Using Collections.addAll method, you can pass a list and an array as arguments which will copy all the elements from the array of objects into the Collection object or precisely List in our case. However, first thing you have to do is to create one blank List object to pass it on to addAll method.

package com.techstackjournal;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ArrayToList {

	public static void main(String[] args) {
		
		String[] arr = {"Alpha", "Beta", "Gamma"};
	
		List list = new ArrayList();

		Collections.addAll(list, arr);
		
		for (Object object : list) {
			System.out.println(object);
		}
		
	}

}

Converting Object Array to List using Java 8 Streams

In this example, we are using the Java 8 Streams API to first collect the array elements and then on to convert it to a List object.

package com.techstackjournal;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class ArrayToList {

	public static void main(String[] args) {

		String[] arr = { "Alpha", "Beta", "Gamma" };

		List list = Arrays.stream(arr).collect(Collectors.toList());

		for (Object object : list) {
			System.out.println(object);
		}

	}

}

Converting Primitive Array to List Using Java 8 Streams

In this example, we are converting a primitive array to List using Java 8 Streams API, which is not possible otherwise. You can see that the collected array elements are getting boxed into the wrapper class Integer. So, once conversion is completed you will have List<Integer>.

package com.techstackjournal;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class ArrayToList {

	public static void main(String[] args) {

		int[] arr = {1,2,3,4,5,6,7,8,9};


		List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());

		for (Object object : list) {
			System.out.println(object);
		}

	}

}