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 5,587 times
12
Erwin Bolwidt
- 29,014
- 15
- 50
- 74
Marlock
- 215
- 2
- 8
-
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
31
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,122
- 12
- 17
-
... 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
-
1
4
How I do it:
val map = mutableMapOf<String, Int>()
map[key] = (map[key] ?: 0) + 1
Kirill Groshkov
- 1,063
- 1
- 15
- 19
0
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,150
- 2
- 8
- 9
0
You can define
fun <T> MutableMap<T, Int>.inc(key: T, more: Int = 1) = merge(key, more, Int::plus)
So you can so something like
map.inc("Example",3)
map.inc("Example")
otherMap.inc(otherObject)
Wael Ellithy
- 89
- 1
- 3