Remove Elements from a Set in Java

In this post, we will see how to remove elements from a Set in Java based on some specified condition.


1. Using an Iterator

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



2. Using removeAll()

The idea here 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 Set#removeAll() method as shown below:

In java 8, we can do like


3. Java 8


3.1. Using Collectors:

Here we convert the specified set to a sequential Stream, filter the stream and accumulate the elements that matches 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 –


3.2. Using forEach() + Set.remove()

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

Below code uses Java 8 Stream for filtering, but an Iterator or a for-each loop can also be used.

Below code performs filtering inside the forEach() method itself –


3.3. Using removeIf()

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

Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Get great deals at Amazon

Leave a Reply

Notify of