Table of Contents
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package org.arpit.java2blog.flatMap; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; public class StreamCollectToArrayMain { public static void main(String args[]) { List<String> listOfCountries=Arrays.asList("India","China","Nepal","Bhutan"); Stream<String> streamCountries=listOfCountries.stream(); String[] countriesArr=streamCountries .toArray(size -> new String[size]); for (String country:countriesArr) { System.out.println(country); } } } |
When you run above program, you will get below output:
China
Nepal
Bhutan
It is recommended to simply use an array constructor reference as below.
Change line no. 15-16 as below.
1 2 3 4 |
String[] countriesArr=streamCountries .toArray(String[]::new); |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package org.arpit.java2blog.flatMap; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; public class StreamCollectToIntArrayMain { public static void main(String args[]) { List<Integer> listOfIntgers=Arrays.asList(12,3,45,65,12,1,78); Stream<Integer> streamIntegers=listOfIntgers.stream(); int[] intArr=streamIntegers.mapToInt(x->x) // Convert Stream to IntStream .toArray(); // you can directly call toArray for (int e:intArr) { System.out.println(e); } } } |
3
45
65
12
1
78
That’s all about converting a Java stream to array in java.