This post will discuss how to remove a key from a Map while iterating over it in Java.

It is not allowed to modify a map in Java while iterating over it to avoid non-deterministic behavior at a later stage. For example, the following code example throws a java.util.ConcurrentModificationException since the remove() method of the Map interface is called during iteration.

Download  Run Code

Output:

Exception in thread “main” java.util.ConcurrentModificationException
    at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1495)
    at java.base/java.util.HashMap$KeyIterator.next(HashMap.java:1518)
    at Main.main(Main.java:16)

1. Using Iterator.remove() method

It is permitted to modify a set while iterating over it using iterator’s remove() method, instead of Map’s remove() method. The following code demonstrates this:

Download  Run Code

Output:

{C++=1980, C=1972, Ruby=1995}

2. Using removeIf() method

For Java 8 and above, you can use the removeIf() method with lambda expressions. The removeIf() method removes all elements from the collection which satisfy the provided predicate. The following code demonstrates its usage:

Download  Run Code

Output:

{Java=1995, JavaScript=1995, Ruby=1995}

 
You can also call the removeIf() method on the set returned by the keySet() method. Both these method works since the returned set view of keys is backed by the map, and any changes made to the set are reflected in the map as well.

Download  Run Code

Output:

{Java=1995, JavaScript=1995, Ruby=1995}

3. Using removeAll() method

Stream API also provides the removeAll() method that removes all elements associated with the specified keys. Here’s a program to demonstrates the working of the removeAll() method:

Download  Run Code

Output:

{C++=1980, C=1972, Ruby=1995}

That’s all about removing a key from a Map while iterating over it in Java.