Scala地图转换

时间:2010-05-24 05:15:17

标签: scala map

我害怕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")}
}

3 个答案:

答案 0 :(得分:8)

您可以使用'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))

答案 1 :(得分:4)

替代Arjan的回答:(只是稍微改变)

scala> val someMap = Map("a" -> "apple", "b" -> "banana")
someMap: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map(a -> apple, b -> banana)

scala> val newMap = someMap map {                                     
     |   case(k , v @ "apple") => (k, "alligator")            
     |   case pair             => pair            
     | }
newMap: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map(a -> alligator, b -> banana)

答案 2 :(得分:2)

更容易:

val myMap = Map("a" -> "apple", "b" -> "banana") 

myMap map {
   case (k, "apple") => (k, "apfel")
   case pair => pair
}