I created a mutableMap<String, Int>
and created a record "Example" to 0
. How can I increase value, f.e. to 0 + 3
?
Asked
Active
Viewed 8,763 times
18

Erwin Bolwidt
- 30,799
- 15
- 56
- 79

Marlock
- 275
- 2
- 9
-
Get value from map, increment it, set new value to map. – talex Dec 18 '18 at 05:37
-
Possible duplicate of [How to increment value of a given key with only one map lookup?](https://stackoverflow.com/questions/53781965/how-to-increment-value-of-a-given-key-with-only-one-map-lookup) – Simulant Dec 18 '18 at 14:47
4 Answers
41
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)

Rene
- 5,730
- 17
- 20
-
... just as a side-note: if you also want to remove some entries on certain conditions, [`Map.compute`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Map.html#compute(K,java.util.function.BiFunction)) may also be helpful... or generally have a look at the [`Map`-interface](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Map.html) then – Roland Dec 18 '18 at 16:29
-
2
-
11
How I do it:
val map = mutableMapOf<String, Int>()
map[key] = (map[key] ?: 0) + 1

Kirill Groshkov
- 1,535
- 1
- 22
- 23
2
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")

Wael Ellithy
- 119
- 1
- 3
1
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

Dushyant Singh
- 1,270
- 2
- 9
- 9