How to remove item by key from a collection of key-value pairs (associative array) in Kotlin

1 Answer

0 votes
// Using an iterator to remove items

fun removeKeyFromMap(targetKey: String) {
    val map = mutableMapOf("d" to 4, "a" to 1, "c" to 3, "b" to 2)
    val iterator = map.entries.iterator()

    while (iterator.hasNext()) {
        val (key, _) = iterator.next()
        if (key == targetKey) {
            iterator.remove()
        }
    }

    for (entry in map.entries) {
        println("Key: ${entry.key}, Value: ${entry.value}")
    }
}

fun main() {
    removeKeyFromMap("b")
}


/*
run:

Key: d, Value: 4
Key: a, Value: 1
Key: c, Value: 3

*/

 



answered Mar 23 by avibootz

Related questions

...