"testing1", "test2" -> "te-6ren">
gpt4 book ai didi

Scala map 转换

转载 作者:行者123 更新时间:2023-12-04 10:21:57 28 4
gpt4 key购买 nike

恐怕我是 Scala 新手:
我正在尝试根据一些简单的逻辑将 Map 转换为新 Map:

val postVals = Map("test" -> "testing1", "test2" -> "testing2", "test3" -> "testing3")

我想测试值“testing1”并更改值(在创建新 map 时)
def modMap(postVals: Map[String, String]): Map[String, String] = {
postVals foreach {case(k, v) => if(v=="testing1") postVals.update(k, "new value")}
}

最佳答案

您可以使用“ map ”方法。通过将给定的函数应用于它的所有元素来返回一个新集合:


scala> def modMap(postVals: Map[String, String]): Map[String, String] = {
postVals map {case(k, v) => if(v == "a") (k -> "other value") else (k ->v)}
}

scala> val m = Map[String, String]("1" -> "a", "2" -> "b")
m: scala.collection.immutable.Map[String,String] = Map((1,a), (2,b))

scala> modMap(m)
res1: Map[String,String] = Map((1,other value), (2,b))

关于Scala map 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2894862/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com