Convert int array to Integer array in Java

In this post, we will see how to convert int array to Integer array using plain Java, Guava and Apache Commons Collections.


 

The Integer class wraps a value of the primitive type 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 –

Naive solution would be to create an array of Integer type and use a regular for loop to assign values to it from primitive integer array.

Java

Download   Run Code

Output:

[1, 2, 3, 4, 5]

 

2. Java 8 –

We can use Java 8 Stream API to convert int 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()

Java8

Download   Run Code

Output:

[1, 2, 3, 4, 5]

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

 

3. Guava

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

Guava

Download   Run Code

Output:

[1, 2, 3, 4, 5]

 

4. Apache Commons Lang Library –

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

Apache

Download

Output:

[1, 2, 3, 4, 5]

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz