This post will discuss how to convert primitive integer array to list of Integer using plain Java, Guava library, and Apache Commons Collections.

1. Naive solution

A naive solution is to create a list of Integer and use a regular for-loop to add elements from a primitive integer array.

Download  Run Code

Output:

[1, 2, 3, 4, 5]

2. Using Java 8

We can use Java 8 Stream to convert a primitive integer array to an Integer list. Following are the steps:

  1. Convert the specified primitive array to a sequential stream using Arrays.stream().
  2. Box each element of the stream to an Integer using IntStream.boxed().
  3. Use Collectors.toList() to accumulate the input elements into a new list.

The following program demonstrates it:

Download  Run Code

Output:

[1, 2, 3, 4, 5]

 
We can also use IntStream.of() to get IntStream from integer array.

 
Here’s another version that uses Stream. First, we convert a primitive integer array to Integer array and then use Collections.addAll() to add all elements of the Integer array to the list of Integer, as shown below:

Download  Run Code

3. Using Guava Library

We can also use Guava’s Ints.asList() to get a fixed-size list view of the specified array, similar to Arrays.asList(). It will return List<Integer> unlike Arrays.asList(), which returns List<int[]>.

Download Code

Output:

[1, 2, 3, 4, 5]

 
Since an array cannot be structurally modified, if we try to add or remove elements from the list, an UnsupportedOperationException will be thrown. If we want a mutable list, we can use:

4. Using Apache Commons Lang

Arrays.asList(int[]) returns a List<int[]> not List<Integer>.

 
To get List<Integer>, we need to convert an array of primitive ints to the Integer array first. We can use the ArrayUtils.toObject() method provided by Apache Commons lang for conversion, as shown below:

That’s all about converting int array to Integer List in Java.