如何迭代标量映射?

我有一张斯卡拉地图:

attrs: Map[String , String]

当我尝试在映射上迭代时;

attrs.foreach { key, value =>     }

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

70481 次浏览

Three options:

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

The trick is that iteration gives you key-value pairs, which you can't split up into a key and value identifier name without either using case or for.

foreach method receives Tuple2[String, String] as argument, not 2 arguments. So you can either use it like tuple:

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

or you can make pattern match:

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

I have added some more ways to iterate map values.

// 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))
}