Converting Array to List in Java

  • Last updated Apr 25, 2024

There are several methods available to convert an array into a list in Java. Here are a few examples that demonstrate efficient ways to convert an array to a list in Java:

Example 1

Here's an example where we have a sample array of string items, strArray. To convert this array to a List, we use Arrays.asList(strArray). This method creates a fixed-size List backed by the provided array, in this case, strArray. So, bookList is a List<String> containing the same elements as strArray, offering a convenient way to work with the array as a list.

// sample array of string items
String[] strArray = { "Science", "English", "Geography", "Economics", "Computer" };

// converting to List
List<String> bookList = Arrays.asList(strArray);
Example 2

In this example, we have a sample array of integer items, intArray. To convert this array to a List, we initialize an empty ArrayList<Integer> named intList. Using a enhanced for loop, each element from the array is iterated over, and then added to the intList. After the loop, intList contains the same integers as intArray, effectively converting the array to a dynamic list.

// sample array of int items
int[] intArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

// converting to list
List<Integer> intList = new ArrayList<Integer>();
for (int i : intArray) {
	intList.add(i);
}
Example 3

Here's the third example where we have a sample array of integer items, intArray. To convert this array to a list, we use Arrays.stream(intArray) to create an IntStream, then boxed() method to convert each int to an Integer, and finally, collect(Collectors.toList()) to gather the elements into a List . This concise stream-based approach efficiently transforms the primitive array into a dynamic list, represented by intList1.

// sample array of int items
int[] intArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

// converting to list example 1
List<Integer> intList1 = Arrays.stream(intArray).boxed().collect(Collectors.<Integer>toList());
Example 4

Here is the fourth example where we have a sample array of integer items, intArray. The code uses a concise stream-based approach: Arrays.stream(intArray) converts the primitive array to an IntStream, boxed() transforms each int to its corresponding Integer, and toList() collects these Integer elements into a List<Integer>, resulting in the variable intList2. This efficient method offers a streamlined way to convert a primitive integer array to a dynamic list in Java.

// sample array of int items
int[] intArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

// converting to list example 2
List<Integer> intList2 =Arrays.stream(intArray).boxed().toList();