Search

Dark theme | Light theme

January 20, 2021

Java Joy: Turn Stream Into An Array

The Java Stream API has many useful methods. If we want to transform a Stream to a Java array we can use the toArray method. Without an argument the result is an object array (Object[]), but we can also use an argument to return an array of another type. The easiest way is to use the contructor of the array type we want as method reference. Then the result is an array of the given type with the elements of the stream.

This is very useful if we have a Java Stream and want to use the elements to invoke a method with a variable arguments parameter. In Java we can pass an array object as variable arguments argument to a method. So if we transform the Stream to an array we can invoke the method with that value.

In the following example we see how we transform a Stream with String values to a String[] object. We use this String[] object to invoke a method with a varargs parameter of type String....

package mrhaki.stream;

import java.util.stream.Stream;

public class Sample {

    public static void main(String[] args) {
        // With the .toArray method we can convert a Stream
        // to an array. 
        // We can use the constructur of the array type
        // we want to convert to as method reference to get 
        // the correct array result.
        final var result = 
            Stream.of("Java", "Clojure", "Groovy", "Kotlin")
                  .filter(language -> language.contains("o"))
                  .toArray(String[]::new);

        assert result[0].equals("Clojure");
        assert result[1].equals("Groovy");
        assert result[2].equals("Kotlin");

        // This is useful with varargs parameters as well,
        // as arrays can be used for a varargs parameter.
        assert "Clojure".equals(first(result));
        assert "Clojure".equals(first("Clojure", "Groovy", "Kotlin"));
    }

    private static String first(String... values) {
        return values[0];
    }
}

Written with Java 15.0.1