This post will discuss how to remove elements from a set in Java based on some specified condition.

1. Using an iterator

We can use the remove() method provided by the Iterator interface that removes the latest element returned by the iterator. Please note we should not modify the set after the iterator is created (except through the iterator’s own remove method); otherwise, a ConcurrentModificationException is thrown.

2. Using removeAll() method

Here, the idea is to maintain a collection of elements from the original set that matches the given condition. Then we remove those elements from the set using the Set#removeAll() method, as shown below:

 
In Java 8, we can do like

3. Using Java 8

⮚ Using Collectors

Here we convert the specified set to a sequential Stream, filter the stream and accumulate the elements that match the given condition into a new set using a Collector.

 
Please note that Collectors#toSet() doesn’t guarantee on the type of the set returned. We can use Collectors#toCollection() instead to specify the desired set type:

⮚ Using forEach() with Set.remove()

Since we can’t modify a set while iterating over it, we can create a duplicate set and remove elements that satisfy the condition from the original set by iterating over the duplicate set.

The following code uses Java 8 Stream for filtering, but we can also use an iterator or a for-each loop.

 
The following code performs filtering inside the forEach() method itself:

⮚ Using removeIf()

Java 8 introduced the Set#removeIf() method that uses Iterator#remove() behind the scenes and removes all elements from the set that satisfies the given condition.

That’s all about removing elements from a Set in Java.