2010-05-24 351 views
7

我是一個新手斯卡拉恐怕: 我想一個地圖轉換成基於一些簡單的邏輯新地圖:斯卡拉地圖轉換

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

我想測試值「 testing1" 並更改值(在創建新地圖)

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

回答

8

您可以使用‘映射’的方法。


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

+2

是,通過施加給定函數的所有元素,則返回一個新的集合非常感謝......我試圖讓我的大腦思考功能,慢慢地但肯定地...... – Vonn 2010-05-24 05:54:57

4

替代阿爾揚的回答是::(只是略有變化)

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

很好,我正在嘗試類似這樣的東西,但無法獲得正確的語法..謝謝 – Vonn 2010-05-24 06:04:06

+0

@Benjamin,T這裏有一個小小的錯誤(在我和Arjan的答案中)。現在糾正了它。 – missingfaktor 2010-05-25 04:26:52

2

更容易:

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

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