Filter Set in Java

In this post, we will illustrate how to filter set in Java.


 

1. Java 7 and less

In Java 7 and less, we can iterate over the set using an advanced for loop and filter elements using a conditional statement.

Download   Run Code

Output:

[C#, C++, C]

Above solution creates a new set for filtered values. We can apply filter to the same set using an iterator. Below code uses remove() method provided by Iterator class to filter elements from same set.

Download   Run Code

Output:

[C#, C++, C]

Please note that ConcurrentModificationException will be thown if remove() method of Set interface is used as it is not permitted to modify a set while iterating over it except by iterator’s own remove method.

 

2. Java 8 and above

In Java 8 and above, we can convert the set into a Stream and filter it using filter() method provided by Stream. Finally we collect the filtered elements in a String.

Download   Run Code

Output:

[C#, C++, C]

 
We can also convert the filtered Stream back to a Set by using a Set collector.

 

Download   Run Code

Output:

[C#, C++, C]

 
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