This post will discuss how to convert a stream to an array in Java.

1. Convert stream<T> to T[]

The Java Stream provides the toArray() method that returns an array containing the stream elements. It has two overloaded versions:

⮚ Using toArray()

It returns an Object[].

Download  Run Code

⮚ Using toArray(IntFunction<A[]> generator)

It accepts an array constructor reference and returns generic A[].

Download  Run Code

 
We can also write our own IntFunction using lambda expressions, as shown below:

Download  Run Code

 
Similarly, we can convert the stream of other types into an array. Let’s take another example of the stream of Integer.

2. Convert stream<Integer> to int[]

Converting a stream of Integer objects to a primitive integer array is not that straightforward in Java.

As seen in the previous section, overloaded versions of Stream.toArray() returns an Object[] and generic A[], respectively, which can’t represent primitive int array. So, we need some stream which can handle primitive type int. Fortunately, Java 8 provides IntStream whose toArray() method returns an int[].

Now the equation reduces to how to convert Stream<Integer> to IntStream. We can use mapToInt() method and provide mapping from Integer to int. There are many ways to map Integer to their primitive form:

⮚ Using method reference

We can provide reference to any method, which returns int such as Integer.getValue() or Number::intValue().

⮚ Explicit unboxing with a lambda expression

 
This works as Integer i type can be inferred by the compiler as we’re operating upon the stream of Integer.

⮚ Auto-unboxing with a lambda expression

 
This implicit unboxing will work since the compiler can determine the result of this lambda must be int. The mapper in mapToInt() is an implementation of ToIntFunction interface, as shown below:

 
And ToIntFunction expects body for applyAsInt() method that produces an int-valued result as evident from its prototype:

Following is the complete code:

Download  Run Code

That’s all about converting Stream to an array in Java.

 
Related Post:

Convert Integer List to an int array in Java

 
Reference: https://stackoverflow.com/questions/960431/how-to-convert-listinteger-to-int-in-java