HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaCritical

How can I convert a Java 8 Stream to an Array?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
arraystreamhowjavaconvertcan

Problem

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 generator) method with an array constructor reference. This is suggested in the API documentation for the method.

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


It finds 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 stringStream = ...;
String[] stringArray = stringStream.toArray(size -> new String[size]);


The purpose of the IntFunction generator is to convert an integer, the size of the array, to a new array.

Example code:

Stream 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

Code Snippets

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

Context

Stack Overflow Q#23079003, score: 1653

Revisions (0)

No revisions yet.