How to convert keys in a Map to lower case?

后端 未结 2 2004
猫巷女王i
猫巷女王i 2020-12-19 03:59

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 lik

相关标签:
2条回答
  • 2020-12-19 04:45

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

    You can use the map method of the Map class with the following one liner:

    val m = Map("a"->"A", "B"->"b1", "b"->"B2", "C"->"c")
    m.map(e=>(e._1.toLowerCase,e._2))
    
    0 讨论(0)
  • 2020-12-19 05:00

    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 map here, rather than a side-effecting function.

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

    If you really want 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)
    
    0 讨论(0)
提交回复
热议问题