This post will discuss how to convert a list of Integer to a primitive integer array in Java.

1. Using Java 8

We can use the Stream provided by Java 8 to convert a list of Integer to a primitive integer array in Java. We start by converting given List<Integer> to Stream<Integer> using List.stream() method. Now all we need to do is convert Stream<Integer> to int[]. Please refer to this post for a detailed explanation of 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. Using Apache Commons Lang

Apache Commons Lang’s ArrayUtils class provides a toPrimitive() method that can convert an Integer array to primitive ints. We need to convert a list of integers to an Integer array 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 them to the function, as shown below:

3. Using Guava Library

Guava’s Ints.toArray() can also convert a list of Integer to a primitive integer array.

Download 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.

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