Convert Stream to Array of specific type in Java 8 ?

0 votes
asked Dec 19, 2017 by Hitesh Garg (352 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, 2018 by Rahul Singh (543 points)  
selected May 25, 2018 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 =
                          .filter(name -> name.length() > 10)

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.