Java Stream collect to array

Java Stream collect to array

In this post, we will see how to collect any Java 8 Stream to array.

There are many ways to do it but I am going to show easiest way.

You can simply use toArray(IntFunction<A[]> generator).This generator function takes size as input and creates new array of that size.

Convert Steam to Array

Let’s understand with the help of simple example.

When you run above program, you will get below output:

India
China
Nepal
Bhutan

It is recommended to simply use an array constructor reference as below.
Change line no. 15-16 as below.

Array constructor reference is just another way of writing aboveLambda expresssion.

Collect Stream to Integer array

If you want to convert to Integer array, you can use IntStream to do it. You can call toArray() on IntStream and it will simply convert it to int[]. You don’t need to pass any argument in this scenario.

12
3
45
65
12
1
78

That’s all about converting a Java stream to array in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *