Java Stream collect to array

Previous
Next

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 above lambda expression.

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 Stream to array in java.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog