如何迭代scala地图?

ace*_*ace 79 scala

我有scala地图:

attrs: Map[String , String]
Run Code Online (Sandbox Code Playgroud)

当我尝试迭代地图时;

attrs.foreach { key, value =>     }
Run Code Online (Sandbox Code Playgroud)

以上不起作用.在每次迭代中,我必须知道什么是关键,什么是价值.使用scala语法糖迭代scala map的正确方法是什么?

Rex*_*err 150

三种选择:

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
Run Code Online (Sandbox Code Playgroud)

诀窍在于迭代为您提供了键值对,您无法使用case或者将其拆分为键和值标识符名称for.


ten*_*shi 72

foreach方法接收Tuple2[String, String]为参数,而不是2个参数.所以你可以像元组一样使用它:

attrs.foreach {keyVal => println(keyVal._1 + "=" + keyVal._2)}
Run Code Online (Sandbox Code Playgroud)

或者你可以进行模式匹配:

attrs.foreach {case(key, value) => ...}
Run Code Online (Sandbox Code Playgroud)

  • 看看雷克斯的答案,那里有更好的选择 (6认同)