简体   繁体   English

Kotlin Map 和计算函数

[英]Kotlin Map and Compute Functions

I am trying to re-compute values for all entries in a mutable map without changing the keys.我试图在不更改密钥的情况下重新计算可变 map 中所有条目的值。

Here is the code (with comments showing what I am expecting)这是代码(注释显示了我的期望)

fun main(args: Array<String>) {

    var exampleMap: MutableMap<Int, String> = mutableMapOf(1 to "One", 2 to "Two")

    // Before it's {1-"One", 2-"Two"}
    with(exampleMap) {
        compute(k){
            _,v -> k.toString + "__" + v
        }
    }

    // Expecting {1->"1__One", 2->"2__Two"}


 }

I don't want to use mapValues because it creates a copy of the original map. I think compute is what I need, but I am struggling to write this function. Or, rather I don't know how to write this.我不想使用mapValues ,因为它创建了原始 map 的副本。我认为compute是我所需要的,但我正在努力编写这个 function。或者,我不知道如何写这个。 I know the equivalent in Java (as I am a Java person) and it would be:我知道 Java 中的等价物(因为我是 Java 人),它将是:

map.entrySet().stream().forEach(e-> map.compute(e.getKey(),(k,v)->(k+"__"+v)));

How can I achieve that in Kotlin with compute ?我怎样才能在 Kotlin 中通过compute实现这一点?

Regards,问候,

The best way to do this is by iterating over the map's entries .最好的方法是遍历地图的entries This ensures you avoid any potential concurrent modification issues that might arise due to modifying the map while iterating over it.这可确保您避免在迭代时修改 map 时可能出现的任何潜在的并发修改问题。

map.entries.forEach { entry ->
    entry.setValue("${entry.key}__${entry.value}")
}

Use onEach function:使用onEach function:

var exampleMap: MutableMap<Int, String> = mutableMapOf(1 to "One", 2 to "Two")
println(exampleMap)
exampleMap.onEach {
   exampleMap[it.key] = "${it.key}__${it.value}"     
}
println(exampleMap)

Output: Output:

{1=One, 2=Two}
{1=1__One, 2=2__Two}

onEach performs the given action on each element and returns the list/array/map itself afterwards. onEach对每个元素执行给定的操作,然后返回列表/数组/地图本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM