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

The Integer class wraps a value of the primitive int in an object. An object of type Integer contains a single field whose type is int and has several useful methods when dealing with an int.

1. Naive solution

A naive solution is to create an array of Integer type and use a regular for-loop to assign values to it 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 Integer array:

  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. Return an Integer array containing elements of this stream using Stream.toArray().

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.

3. Using Guava Library

We can also use Guava API to convert a primitive integer array to the Integer array. The idea is to get a fixed-size list using Ints.asList() and call List.toArray() to get an Integer array.

Download Code

Output:

[1, 2, 3, 4, 5]

4. Using Apache Commons Lang

We can directly use Apache Commons lang’s ArrayUtils.toObject() method to convert an array of primitive ints to objects, as shown below:

Download Code

Output:

[1, 2, 3, 4, 5]

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