Reputation: 285
I created a mutableMap<String, Int>
and created a record "Example" to 0
. How can I increase value, f.e. to 0 + 3
?
Upvotes: 19
Views: 12438
Reputation: 119
You can define
fun <K> MutableMap<K, Int>.inc(key: K): Int = merge(key, 1, Math::addExact)!!
So you can so something like
map.inc("Example")
Upvotes: 2
Reputation: 1771
How I do it:
val map = mutableMapOf<String, Int>()
map[key] = (map[key] ?: 0) + 1
Upvotes: 13
Reputation: 1607
You can use getOrDefault if API level is greater than 23. Otherwise you can use elvis operator
val map = mutableMapOf<String,Int>()
val value = map["Example"] ?: 0
map["Example"] = value + 3
Upvotes: 1
Reputation: 6258
You could use the getOrDefault
function to get the old value or 0, add the new value and assign it back to the map.
val map = mutableMapOf<String,Int>()
map["Example"] = map.getOrDefault("Example", 0) + 3
Or use the merge
function from the standard Map
interface.
val map = mutableMapOf<String,Int>()
map.merge("Example", 3) {
old, value -> old + value
}
Or more compact:
map.merge("Example",3, Int::plus)
Upvotes: 42