scala 如何将 Map 中的键转换为小写?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29369984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 07:01:36  来源:igfitidea点击:

How to convert keys in a Map to lower case?

scaladictionarycollections

提问by placplacboom

I have a map where the key is a String and I need to change every key to lower case before work with this map.

我有一个地图,其中键是一个字符串,在使用此地图之前,我需要将每个键更改为小写。

How can I do it in Scala? I was thinking something like:

我怎样才能在 Scala 中做到这一点?我在想这样的事情:

var newMap = scala.collection.mutable.Map[String, String]()
data.foreach(d => newMap +=(d._1.toLowerCase -> d._2))   

What is the best approach for it? Thanks in advance.

什么是最好的方法?提前致谢。

采纳答案by Michael Zajac

The problem here is that you're trying to add the lower-cased keys to the mutable Map, which is just going to pile additional keys into it. It would be better to just use a strict maphere, rather than a side-effecting function.

这里的问题是您试图将小写的键添加到 mutable 中Map,这只是将额外的键堆入其中。最好在map这里只使用一个严格的,而不是一个副作用函数。

val data = scala.collection.mutable.Map[String, String]("A" -> "1", "Bb" -> "aaa")
val newData = data.map { case (key, value) => key.toLowerCase -> value }

If you reallywant to do it in a mutable way, then you have to remove the old keys.

如果您真的想以可变方式进行操作,则必须删除旧密钥。

data.foreach { case (key, value) =>
    data -= key
    data += key.toLowerCase -> value
}

scala> data
res79: scala.collection.mutable.Map[String,String] = Map(bb -> aaa, a -> 1)

回答by Gregor Rayman

Your approach would work, but in general in Scala for this kind of transformation the immutable variants of the collections are preferred.

您的方法会起作用,但通常在 Scala 中,对于这种转换,集合的不可变变体是首选。

You can use the mapmethod of the Mapclass with the following one liner:

您可以mapMap类的方法与以下一个衬垫一起使用:

val m = Map("a"->"A", "B"->"b1", "b"->"B2", "C"->"c")
m.map(e=>(e._1.toLowerCase,e._2))