Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Map conversion

Tags:

map

scala

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")}
}
like image 803
Vonn Avatar asked May 24 '10 05:05

Vonn


People also ask

How do I convert a list to map in Scala?

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.

Is Scala map a HashMap?

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.


2 Answers

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

like image 60
Arjan Blokzijl Avatar answered Sep 23 '22 13:09

Arjan Blokzijl


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)
like image 37
missingfaktor Avatar answered Sep 20 '22 13:09

missingfaktor