Convert Stream to an Array in Java

In this post, we will see how to convert stream to an array in Java.


1. Convert stream<T> to T[ ]

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


1. toArray()

It returns an Object[].

Download   Run Code


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

In similar way, we can convert Stream of other types into array. Let’s take another example of stream of Integer.


2. Convert stream<Integer> to int[ ]

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

As seen in 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() function and provide mapping from Integer to int. There are many ways to map Integers to their primitive form:

1. Method reference

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

2. Explicit unboxing with lambda expression

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

3. Auto-unboxing with lambda expression

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

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

Below is the complete code:

Download   Run Code

Related Post: Convert List of Integer to array of int


1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of