Monday, 29 August 2016

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?


Answer



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);


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 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

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...