What is the most efficient way to modify the value...
# announcements
c
What is the most efficient way to modify the values of an immutable
Map<K,V>
using is Key?
d
I assume you mean "make a new map", because obviously you can't modify an immutable map. I would do
Copy code
val newMap = map.toMutableMap()
newMap[key] = newValue
c
I was thinking of something like:
Copy code
myMap.map {
    if(it.key == currentKey)
        //modify his values
    else 
        //return the original Map.Entry
}
d
That's less efficient most likely.
c
Thanks! i´m going to try your solution
r
val newMap = map + (key to value)
🔝 2
K 5
c
I was just creating this function:
Copy code
fun <K, V> Map<K, V>.replace(key: K, values: V) =
    toMutableMap().apply { this[key] = values }
😅
m
Misleading, isn’t it? It suggests that it modifies the (immutable) map in place, but depending on what toMutableMap() does (or will do in the future), it might copy the data and return a new map (which is the current implementation). You could call it
with
or
copy
and make it return an immutable map again.
👍 1
c
Copy code
fun <K, V> Map<K, V>.copy(key: K, values: V): Map<K, V> =
    toMutableMap().apply { this[key] = values }
return an immutable map again explicitly it's really a good point