oshai
oshai

Reputation: 15375

How to filter a Mutable Map in place in Kotlin

I would like to remove items from a MutableMap, similar to filter.
In list I can use removeAll { } and retainAll { }
(see this question: How to filter a list in-place with Kotlin?).

Is there something similar for Mutable Maps?

EDIT:

I found that entries property of Map has those methods.

Upvotes: 12

Views: 4758

Answers (1)

hotkey
hotkey

Reputation: 148169

One option would be to operate on the map's keys: MutableSet<K>, where you can use removeAll { ... } or retainAll { ... } just as you would with a list:

val m = mutableMapOf(1 to "a", 2 to "b")
m.keys.removeAll { it % 2 == 0 }
println(m) // {1=a}

(runnable sample)

If just keys are not enough for the predicate, you can simply do the same with the map's entry set, entries: MutableSet<MutableEntry<K, V>>

val m = mutableMapOf(1 to "a", 2 to "b", 3 to "c")
m.entries.retainAll { it.key < 3 }
m.entries.removeAll { (k, v) -> k == 1 && v == "a" }
println(m) // {2=b}

(runnable sample)

Upvotes: 18

Related Questions