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.
There are also two specific ways for filtering maps: by keys and by values. For each way, there is a function: filterKeys() and filterValues() . Both return a new map of entries which match the given predicate. The predicate for filterKeys() checks only the element keys, the one for filterValues() checks only values.
Kotlin MutableMap is an interface of collection frameworks which contains objects in the form of keys and values. It allows the user to efficiently retrieve the values corresponding to each key. The key and values can be of the different pairs like <Int, String>, < Char, String>, etc.
Kotlin Map : mapOf() Kotlin distinguishes between immutable and mutable maps. Immutable maps created with mapOf() means these are read-only and mutable maps created with mutableMapOf() means we can perform read and write both. The first value of the pair is the key and the second is the value of the corresponding key.
Yes, it will. The reference for mutableMapOf() says: The returned map preserves the entry iteration order.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With