Convert Stream to Array of specific type in Java 8 ?

0 votes
88 views
asked Dec 19, 2017 by Hitesh Garg (343 points)  

What is the best and the easiest way to convert a Java 8 Stream into an array of a Specific type?

1 Answer

0 votes
answered May 24 by Rahul Singh (518 points)  
selected May 25 by Hitesh Garg
 
Best answer

This can be done using toArray(String[]::new) as the terminal operation on the stream.

toArray(size -> new String[size]) or toArray(String[]::new).

To filter out names with length greater than 10 characters -

String[] men = names.stream()
                          .filter(name -> name.length() > 10)
                          .toArray(String[]::new);

In this example the terminal method toArray(String[]::new) converts the resulting array to the String[] type.
We can use the specific type in this method and it will convert it the mentioned type only if it is possible to do so.

Welcome to Codingeek Q&A, where you can ask questions and receive answers from other members of the community.
...