如何迭代Scala地图?


81

我有scala地图:

attrs: Map[String , String]

当我尝试遍历地图时;

attrs.foreach { key, value =>     }

以上不起作用。在每次迭代中,我必须知道什么是键,什么是值。使用scala语法糖在scala映射上进行迭代的正确方法是什么?

Answers:


72

foreach方法接收Tuple2[String, String]作为参数,而不是2个参数。因此,您可以像元组一样使用它:

attrs.foreach {keyVal => println(keyVal._1 + "=" + keyVal._2)}

或者您可以使模式匹配:

attrs.foreach {case(key, value) => ...}

6
看看雷克斯的答案,那里有更好的选择
iwein

156

三种选择:

attrs.foreach( kv => ... )          // kv._1 is the key, kv._2 is the value
attrs.foreach{ case (k,v) => ... }  // k is the key, v is the value
for ((k,v) <- attrs) { ... }        // k is the key, v is the value

诀窍是迭代为您提供了键-值对,如果不使用case或,就不能将其拆分为键和值标识符名称for


1

我添加了更多的方法来迭代映射值。

// Traversing a Map
  def printMapValue(map: collection.mutable.Map[String, String]): Unit = {

    // foreach and tuples
    map.foreach( mapValue => println(mapValue._1 +" : "+ mapValue._2))

    // foreach and case
    map.foreach{ case (key, value) => println(s"$key : $value") }

    // for loop
    for ((key,value) <- map) println(s"$key : $value")

    // using keys
    map.keys.foreach( key => println(key + " : "+map.get(key)))

    // using values
    map.values.foreach( value => println(value))
  }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.