java – How to convert a Java 8 stream to an array?

You can convert a Java 8 stream to an array using this simple block of code:

 String[] myNewArray3 = myNewStream.toArray(String[]::new);

But let’s explain things better, first, let’s create a list of strings filled with three values:

String[] stringList = {"Bachiri","Taoufiq","Abderrahman"};

Create a flow from the provided matrix:

Stream stringStream = Arrays.stream(stringList);

now we can perform some operations on this stream

Stream myNewStream = stringStream.map(s -> s.toUpperCase());

and finally convert it to a Java 8 array using these methods:

Method 1-Classic (functional interface)

IntFunction intFunction = new IntFunction() {
    @Override
    public String[] apply(int value) {
        return new String[value];
    }
};


String[] myNewArray = myNewStream.toArray(intFunction);

2 expression -Lambda

 String[] myNewArray2 = myNewStream.toArray(value -> new String[value]);

3- Reference method

String[] myNewArray3 = myNewStream.toArray(String[]::new);

Reference method Explanation:

It is another way of writing a lambda expression that is strictly equivalent to the other.

Leave a comment