Convert a Set to Stream in Java 8

In this post, we will see how to convert a set to stream in Java 8. We will also learn how to apply filters on a stream and convert stream 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.

Java

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 below example, we will create a stream of Integer objects using Collection.stream() and filter it to produce a stream containing only even numbers.

Java

Download   Run Code

Output:

2
4

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

 

3. Convert Stream back to Set

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

Java

Download   Run Code

Output:

[1, 2, 3, 4, 5]

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

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of