Convert Stream to a List in Java 8

In this post, we will see how to convert stream to a list in Java 8.

 

1. Using Collectors

We can collect elements of a stream in a container using Stream.collect() method which accepts a Collector. We can pass Collector returned by Collectors.toList() that accumulates the elements of stream into a new List. This is the standard way to convert stream to a list in Java 8.

 
But Collectors.toList() doesn’t guarantees on the type of the List returned. To have more control over the returned List, we can use Collectors.toCollection() method that can accept a constructor reference to the desired List.

 

2. Divide & Conquer

We can easily divide the problem into two parts:

1. Convert Stream to an Array
2. Convert Array to a List

 

 

3. Using forEach

We can also loop through all elements of the Stream using forEach() method and use list.add() to add each element into an empty List.

 
Please note that if Stream is parallel, then elements may not be processed in original order with forEach() method. We can use forEachOrdered() method to preserve the original order as shown below:

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz