This article explores different ways to remove the mapping for a key from a Map in Kotlin.

1. Using remove() function

The standard solution is to remove a key from a Map in Kotlin is using the remove() function. When the remove() function is called upon a key k, the mapping from key k to value v is removed from the map.

Download Code

 
To remove multiple keys from the map, a better solution is to use the removeAll() function:

Download Code

2. Using removeIf() function

Another option is to use the removeIf() function to remove all mappings from the map that satisfy the specified predicate. It can be used as follows:

Download Code

 
The following code example shows invocation for this function on the mutable set of all keys present in the map.

Download Code

3. Using filterKeys() function

All the above solutions remove the key from the original map. If you need a new instance of the map with the specified key removed, use the filterKeys() function.

Download Code

 
If you need to filter the map based on values, use the filterValues() function:

Download Code

4. Using mapNotNull() function

The mapNotNull() function returns a list containing only the non-null results of applying the given transform function to each entry in the original map. It can be used as follows to remove, replace, or retain a mapping based on a key:

Download Code

 
Alternatively, remove, replace, or retain a mapping based on a value as follows:

Download Code

 
Also See:

Remove a key from a Map in Kotlin while iterating over it

That’s all about removing mapping for a key from a Map in Kotlin.