Convert List of Integer to array of int in Java

In this post, we will see how to convert list of integer to array of int in Java.


 

1. Java 8 –

We can use Stream API provided by Java 8 to convert list of integer to array of int in Java. We start by converting given List<Integer> to Stream<Integer> using List.stream() function. Now all we need to do is convert Stream<Integer> to int[]. Please refer this post for detailed explanation on it.

 

Download   Run Code

Output:

[1, 2, 3, 4, 5]

 

How to handle null values in the list?

 
IntStream.toArray() throws a NullPointerException if any null values are present in the list. There are many options to handle null values:

1. Filter out the null values before mapping:

2. Map the null values to a default value:

3. Handle null inside the lambda expression itself:

 

2. Apache Commons Lang

Apache Commons Lang’s ArrayUtils class provides toPrimitive() method that can convert an array of object Integers to primitive ints. We need to convert list of integers to array of Integers first. We can use List.toArray() for easy conversion.

 

 

toPrimitive() throws a NullPointerException if any null values are present in the list. We can filter null values before passing it to the function as shown below:

 

 

3. Guava

Guava’s Ints.toArray() can also be used to convert list of integer to array of int.

 

Download   Run Code

Output:

[1, 2, 3, 4, 5]

 
Ints.toArray() throws a NullPointerException if any null values are present in the list. We can filter null values before passing it to Ints.toArray() as seen in previous sections.

 

 
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 🙂
 

Get great deals at Amazon




Leave a Reply

avatar
  Subscribe  
Notify of