This post will discuss how to convert a stream to a set in Java.

1. Using Collectors

We can collect elements of a stream in a container using the Stream.collect() method, which accepts a Collector. We can pass the collector returned by Collectors.toSet() that accumulates the elements of the stream into a new Set. This is the standard way to convert a stream to a set in Java 8 and above.

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

2. Using Divide & Conquer

We can easily divide the problem into two parts:

3. Using forEach() method

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

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

That’s all about converting Stream to a Set in Java.