3

I've a Map where the key is a String and the value is an Int but represented as a String.

scala> val m = Map( "a" -> "1", "b" -> "2", "c" -> "3" ) 
m: scala.collection.immutable.Map[String,String] = Map(a -> 1, b -> 2, c -> 3)

Now I want to convert this into a Map[String, Int]

Soumya Simanta
  • 11,523
  • 24
  • 106
  • 161

2 Answers2

12
scala> m.mapValues(_.toInt)
res0: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2, c -> 3)
Brian
  • 20,195
  • 6
  • 34
  • 55
  • 1
    Beware: unlike most collection transformations in Scala, `mapValues` is lazy - transforming function is applied every single time when referring to map values. – ghik Mar 30 '14 at 21:56
6

As shown in Brian's answer, mapValues is the best way to do this.

You can achieve the same effect using pattern matching, which would look like this:

m.map{ case (k, v) => (k, v.toInt)}

and is useful in other situations (e.g. if you want to change the key as well).

Remember that you are pattern matching against each entry in the Map, represented as a tuple2, not against the Map as a whole.

You also have to use curly braces {} around the case statement, to keep the compiler happy.

DNA
  • 42,007
  • 12
  • 107
  • 146
  • The curly braces are not mandatory, but stylistically better. – euphoria83 Mar 28 '14 at 22:31
  • In this particular case (no pun intended), they are required. Replacing them with round parentheses produces: `error: illegal start of simple expression`. See also http://stackoverflow.com/a/4387118/699224 – DNA Mar 28 '14 at 22:39