This post will discuss how to convert a set 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 Set<Integer> to a primitive integer array. Following are the complete steps with an explanation:

  1. Convert given Set<Integer> to Stream<Integer> using Set.stream() method.
  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 Integer to their primitive form:

    mapToInt(Integer::intValue)    // method reference
    mapToInt(i -> i.intValue())    // Explicit unboxing with a lambda expression
    mapToInt(i -> i)                               // Implicit auto-unboxing with a lambda expression

    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. Using Guava Library

    Guava’s Ints.toArray() can also convert a Set<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 set. We can filter null values before passing it to Ints.toArray() as seen before.

    3. Using Apache Commons Lang

    Apache Commons Lang’s ArrayUtils class provides a toPrimitive() method that can convert an Integer object array to array of primitive ints. We need to convert a Set<Integer> to a primitive integer array first. We can use Set.toArray() for easy conversion.

    Download Code

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

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