In this post, we’ll 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]

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

Download  Run Code

Output:

[C#, C++, C]

 
Please note that ConcurrentModificationException will be thrown if the 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 the 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]

 
This is equivalent to:

Download  Run Code

Output:

[C#, C++, C]

That’s all about filtering Set in Java.