Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increase value in mutable map

Tags:

kotlin

I created a mutableMap<String, Int> and created a record "Example" to 0. How can I increase value, f.e. to 0 + 3 ?

like image 882
Marlock Avatar asked Dec 18 '18 05:12

Marlock


2 Answers

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)
like image 127
Rene Avatar answered Oct 23 '22 04:10

Rene


How I do it:

val map = mutableMapOf<String, Int>()

map[key] = (map[key] ?: 0) + 1
like image 23
Kirill Groshkov Avatar answered Oct 23 '22 03:10

Kirill Groshkov