如何仅通过一次地图查找来增加给定键的值? [英] How to increment value of a given key with only one map lookup?
问题描述
说我有一张地图:
var inventory = mutableMapOf("apples" to 1, "oranges" to 2)
我想将苹果的数量增加一个.
and I want to increment the number of apples by one.
但是这不起作用:
inventory["apples"]!!++ // Error:(9, 4) Variable expected
这都不是
var apples = inventory["apples"]!!
++apples
println(inventory["apples"]) // prints "1" => the value was not incremented.
这令人惊讶,因为在Kotlin中,将数字装箱在实例中时将其装箱通用对象.我不希望正在制作副本.
Which is surprising, since in Kotlin, numbers are boxed when they are stored in instances of generic objects. I would not expect that a copy is being made.
似乎唯一的方法是执行以下操作:
It seems that the only way is to do something like:
var apples = inventory["apples"]!!
++apples
inventory["apples"] = apples
println(inventory["apples"])
两者都在地图中使用两次查找,而且非常丑陋且冗长.
Which both uses two lookups in the map and is extremely ugly and lengthy.
有没有一种方法可以仅使用一次查找来增加给定键的值?
Is there a way to increment a value of a given key using only one lookup?
还可以有人解释为什么前两种方法不起作用吗?
Also, could someone explain why the first two methods do not work?
推荐答案
仅使用一个get
而不使用put
,就无法增加该值.之后,您总是需要执行put
,因为Int
是不可变的. inc()
方法(++
是该方法的快捷方式)返回需要存储在映射中的新值.它不会更改存储的值.
There is no way to increment the value with only one get
and without a put
. You always need to do a put
afterwards, because Int
is immutable. The inc()
method (++
is a shortcut for that) returns a new value that need to be stored in the map. It does not change the stored value.
您可以使用
inventory.computeIfPresent("apples") { _, v -> v + 1 }
要将其写在一行中,但是如果您查看实现,它还将执行get()
,然后计算新值,然后执行put()
.因此,您可以节省必须编写的代码行,但不会节省执行时间上的CPU周期.
To write it in one line, but if you look into the implementation it will also do a get()
then compute the new value and do a put()
afterwards. So you can save a line of code you have to write, but you will not save CPU cycles on execution time.
这篇关于如何仅通过一次地图查找来增加给定键的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!