tags:

views:

96

answers:

3

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

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)

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

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

Arjan Blokzijl
Many thanks... I"m trying to get my brain to think functionally. Slowly but surely ...
Vonn
+2  A: 

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

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)
missingfaktor
ahh nice. I was trying something like this but couldn't get the syntax right. Thanks.
Vonn
@Benjamin, There was a slight mistake (in both my and Arjan's answers.) Corrected it now.
missingfaktor
A: 

Just add an updating pair with the plus-sign:

val someMap = Map ("a" -> "apple", "b" -> "banana")
val upd = someMap + ("a" -> "ananas") 
user unknown
Wrong. This would add a new pair when the specified value does not already exist in the map, which is not what is intended.
missingfaktor
Oh, yes, I've overseen that. And that it is based on the value, not the key.
user unknown