Increase value in mutable map

假如想象 提交于 2020-12-12 11:41:07

问题


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


回答1:


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)



回答2:


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



回答3:


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)


来源:https://stackoverflow.com/questions/53826903/increase-value-in-mutable-map

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!