0
0
KotlinHow-ToBeginner · 3 min read

How to Remove Entry from Map in Kotlin: Simple Guide

In Kotlin, you can remove an entry from a mutable map using the remove(key) function, which deletes the entry with the specified key. This function returns the removed value or null if the key was not found.
📐

Syntax

The basic syntax to remove an entry from a mutable map is:

  • map.remove(key): Removes the entry with the given key from the map.
  • Returns the value associated with the removed key, or null if the key was not present.
kotlin
val map = mutableMapOf("a" to 1, "b" to 2)
val removedValue = map.remove("a")
💻

Example

This example shows how to create a mutable map, remove an entry by key, and print the map before and after removal.

kotlin
fun main() {
    val map = mutableMapOf("apple" to 10, "banana" to 20, "cherry" to 30)
    println("Original map: $map")

    val removed = map.remove("banana")
    println("Removed value: $removed")
    println("Map after removal: $map")
}
Output
Original map: {apple=10, banana=20, cherry=30} Removed value: 20 Map after removal: {apple=10, cherry=30}
⚠️

Common Pitfalls

One common mistake is trying to remove an entry from an immutable map, which will cause a compilation error because immutable maps do not support modification.

Also, calling remove(key) on a mutable map with a key that does not exist returns null and does not change the map.

kotlin
fun main() {
    val immutableMap = mapOf("x" to 1, "y" to 2)
    // immutableMap.remove("x") // This line would cause a compile error

    val mutableMap = mutableMapOf("x" to 1, "y" to 2)
    val result = mutableMap.remove("z")
    println("Result of removing non-existing key: $result")
    println("Map after trying to remove non-existing key: $mutableMap")
}
Output
Result of removing non-existing key: null Map after trying to remove non-existing key: {x=1, y=2}
📊

Quick Reference

OperationDescriptionExample
Remove entryDeletes entry by key from mutable mapmap.remove("key")
Return valueReturns removed value or null if key not foundval v = map.remove("key")
Immutable mapCannot remove entries; causes compile errorval map = mapOf(...); map.remove("key") // error

Key Takeaways

Use mutableMapOf and remove(key) to delete entries from a Kotlin map.
remove(key) returns the removed value or null if the key is absent.
Immutable maps cannot be modified; use mutable maps to remove entries.
Removing a non-existing key does not change the map and returns null.