Scala 地图转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2894862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 02:10:29  来源:igfitidea点击:

Scala Map conversion

scalamap

提问by Vonn

I'm a Scala newbie I'm afraid: I'm trying to convert a Map to a new Map based on some simple logic:

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

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

I want to test for value "testing1" and change the value (while creating a new Map)

我想测试值“testing1”并更改值(在创建新地图时)

def modMap(postVals: Map[String, String]): Map[String, String] = {
  postVals foreach {case(k, v) => if(v=="testing1") postVals.update(k, "new value")}
}

回答by Arjan Blokzijl

You could use the 'map' method. That returns a new collection by applying the given function to all elements of it:

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


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))

回答by missingfaktor

Alternative to Arjan's answer: (just a slight change)

替代 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)

回答by gun

even easier:

更简单:

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

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