This article explores different ways to remove a key from a Map in Kotlin while iterating over it.

In Kotlin, you cannot remove a key from a Map while iterating over it. For instance, consider the following code which calls the remove() function during iteration, resulting in a ConcurrentModificationException.

Download Code

Output:

Exception in thread “main” java.util.ConcurrentModificationException
    at java.base/java.util.LinkedHashMap$LinkedHashIterator.nextNode(LinkedHashMap.java:719)
    at java.base/java.util.LinkedHashMap$LinkedKeyIterator.next(LinkedHashMap.java:741)
    at MainKt.main(Main.kt:5)
    at MainKt.main(Main.kt)

 
This post provides an overview of some of the available alternatives to accomplish this.

1. Using Iterator.remove() function

You can use the remove() function of the iterator to filter the map. It is allowed to modify a set while iterating over it if the iterator’s own remove() method is used, and ConcurrentModificationException will not be thrown.

Download Code

Output:

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

2. Using removeIf() function

Another option is to use the removeIf() function without explicitly accessing the iterator. It removes all entries from the map that match a predicate. A typical invocation for this method would look like:

Download Code

Output:

{Ruby=1995, Kotlin=2011}

 
This works since the returned set is backed by the map, and all changes made to this set are reflected in the map as well. Alternatively, you can call the removeIf() function on the mutable set of keys returned by the keys property.

Download Code

Output:

{Ruby=1995, Kotlin=2011}

3. Using removeAll() function

If you need to remove all mappings associated with the specified keys, consider using the removeAll() function. The following program demonstrates its usage:

Download Code

Output:

{C=1972, Ruby=1995}

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