Search code examples
javaarraysjava-8java-stream

How to convert a Java 8 Stream to an Array?


What is the easiest/shortest way to convert a Java 8 Stream into an array?


Solution

  • The easiest method is to use the toArray(IntFunction<A[]> generator) method with an array constructor reference. This is suggested in the API documentation for the method.

    String[] stringArray = stringStream.toArray(String[]::new);
    

    What it does is find a method that takes in an integer (the size) as argument, and returns a String[], which is exactly what (one of the overloads of) new String[] does.

    You could also write your own IntFunction:

    Stream<String> stringStream = ...;
    String[] stringArray = stringStream.toArray(size -> new String[size]);
    

    The purpose of the IntFunction<A[]> generator is to convert an integer, the size of the array, to a new array.

    Example code:

    Stream<String> stringStream = Stream.of("a", "b", "c");
    String[] stringArray = stringStream.toArray(size -> new String[size]);
    Arrays.stream(stringArray).forEach(System.out::println);
    

    Prints:

    a
    b
    c