增加可变地图中的价值 [英] Increase value in mutable map
本文介绍了增加可变地图中的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了mutableMap<String, Int>
,并创建了0
的记录"Example".我如何增加价值到0 + 3
吗?
I created a mutableMap<String, Int>
and created a record "Example" to 0
. How can I increase value, f.e. to 0 + 3
?
推荐答案
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
或使用Map界面中的rel ="noreferrer"> merge
函数.
Or use the merge
function from the standard Map
interface.
val map = mutableMapOf<String,Int>()
map.merge("Example", 3) {
old, value -> old + value
}
或更紧凑:
map.merge("Example",3, Int::plus)
这篇关于增加可变地图中的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文