Convert Stream to a Set in Java 8

In this post, we will see how to convert stream to a set 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.toSet() that accumulates the elements of stream into a new Set. This is the standard way to convert stream to a set in Java 8.

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

 

2. Divide & Conquer

We can easily divide the problem into two parts:

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

 

 

3. Using forEach

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

 
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