Convert Set of Integer to array of int in Java

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


 

1. Java 8 –

We can use Stream API provided by Java 8 to convert set of integer to array of int. Below are the complete steps with explanation:

1. Convert given Set<Integer> to Stream<Integer> using Set.stream() function.

2. Convert Stream<Integer> to IntStream.

We can’t directly convert Stream<Integer> to int[] as Stream.toArray() returns an Object[] and Stream.toArray(IntFunction<A[]>) returns a generic A[]. Fortunately, we have IntStream that can handle primitive int, whose toArray() method returns int[]. Now the problem reduces to how to convert Stream<Integer> to IntStream. There are many ways to map Integers to their primitive form:

Java

Download   Run Code

Output:

[1, 2, 3, 4, 5]

 
IntStream.toArray() throws a NullPointerException if any null values are present in the set. We can easily filter out the null values before mapping:

 

2. Guava

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

Java

Download   Run Code

Output:

[1, 2, 3, 4, 5]

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

 

3. 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 set of integers to array of Integers first. We can use Set.toArray() for easy conversion.

Java

toPrimitive() throws a NullPointerException if any null values are present in the set. We can filter null values before passing it to the function 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