简体   繁体   English

在Scala中将Map [String,String]转换为Map [String,Int]

[英]Convert a Map[String, String] to Map[String, Int] in Scala

I've a Map where the key is a String and the value is an Int but represented as a String. 我有一个Map,其中键是一个String,值是一个Int,但表示为一个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] 现在我想将其转换为Map[String, Int]

scala> m.mapValues(_.toInt)
res0: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2, c -> 3)

As shown in Brian's answer, mapValues is the best way to do this. 如Brian的回答所示, mapValues是执行此操作的最佳方式。

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 (eg 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. 请记住,您对Map中的每个条目进行模式匹配,表示为tuple2,而不是整个Map

You also have to use curly braces {} around the case statement, to keep the compiler happy. 你还必须在case语句周围使用花括号{}来保持编译器的快乐。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM