Convert int array to List of Integer in Java

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


 

1. Naive –

Naive solution would be to create a List of Integer type and use a regular for loop to add elements to it from primitive int 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 list of Integer. Below 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.

Java 8

Download   Run Code

Output:

[1, 2, 3, 4, 5]

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

 
Here’s another version that uses Stream API. First we convert int 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. Guava –

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[]>.

Guava

Download   Run 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. Apache Commons lang –

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

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

 
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