Convert Stream to Array of specific type in Java 8 ?

0 votes
555 views
asked Dec 18, 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

+1 vote
answered May 23, 2018 by Rahul Singh (553 points)  
selected May 24, 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 = 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.

commented Jul 18 by Rita (10 points)  
As the terminal operation on the stream. We can use the specific type in this method and it will convert.
Welcome to Codingeek Q&A, where you can ask questions and receive answers from other members of the community.
...