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]

0

2 Answers 2

12
scala> m.mapValues(_.toInt)
res0: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2, c -> 3)
Sign up to request clarification or add additional context in comments.

1 Comment

Beware: unlike most collection transformations in Scala, mapValues is lazy - transforming function is applied every single time when referring to map values.
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.

2 Comments

The curly braces are not mandatory, but stylistically better.
In this particular case (no pun intended), they are required. Replacing them with round parentheses produces: error: illegal start of simple expression. See also stackoverflow.com/a/4387118/699224

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.