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.

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:

India
China
Nepal
Bhutan

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

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.

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);
        }
    }
}
12
3
45
65
12
1
78

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

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.