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")}
}
To convert a list into a map in Scala, we use the toMap method. We must remember that a map contains a pair of values, i.e., key-value pair, whereas a list contains only single values. So we have two ways to do so: Using the zipWithIndex method to add indices as the keys to the list.
Scala map is a collection of key/value pairs. Any value can be retrieved based on its key. Keys are unique in the Map, but values need not be unique.
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))
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With