This post will discuss how to convert a set to stream in Java 8 and above. We will also learn how to apply a filter on a stream and convert it back to a set or list.

1. Convert a set to stream

Converting a set to stream is very simple. Set interface extends Collection interface and Collection has stream() method that returns a sequential stream of the collection.

Download  Run Code

Output:

[1, 2, 3, 4, 5]

2. Filter stream using a predicate

For filtering a stream, we can use filter(Predicate) that returns a stream consisting of elements that match the given predicate.

In the following example, we’ll create a stream of Integer objects using Collection.stream() and filter it to produce a stream containing only even numbers.

Download  Run Code

Output:

2
4

 
We can also specify a lambda expression or method reference in place of the predicate:

3. Convert stream back to set

We can accumulate the stream elements into a new set using a Collector returned by Collectors.toList().

Download  Run Code

Output:

[1, 2, 3, 4, 5]

 
We can also accumulate the stream elements in a new list using Collectors.toList(), as shown below:

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