Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 268
oshai Avatar asked Oct 15 '18 05:10

oshai


People also ask

How do you filter a map in Kotlin?

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.

Is map mutable in Kotlin?

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.

Is map immutable in Kotlin?

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.

Does map preserve order Kotlin?

Yes, it will. The reference for mutableMapOf() says: The returned map preserves the entry iteration order.


1 Answers

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)

like image 51
hotkey Avatar answered Sep 24 '22 01:09

hotkey