scala 如何迭代scala地图?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6364468/
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
How to iterate scala map?
提问by ace
I have scala map:
我有 Scala 地图:
attrs: Map[String , String]
When I try to iterate over map like;
当我尝试遍历地图时;
attrs.foreach { key, value => }
the above does not work. In each iteration I must know what is the key and what is the value. What is the proper way to iterate over scala map using scala syntactic sugar?
以上不起作用。在每次迭代中,我必须知道什么是关键,什么是价值。使用 Scala 语法糖迭代 Scala 映射的正确方法是什么?
采纳答案by tenshi
foreachmethod receives Tuple2[String, String]as argument, not 2 arguments. So you can either use it like tuple:
foreach方法接收Tuple2[String, String]作为参数,而不是 2 个参数。所以你可以像元组一样使用它:
attrs.foreach {keyVal => println(keyVal._1 + "=" + keyVal._2)}
or you can make pattern match:
或者您可以进行模式匹配:
attrs.foreach {case(key, value) => ...}
回答by Rex Kerr
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 caseor for.
诀窍是迭代为您提供键值对,您不能在不使用case或 的情况下将其拆分为键和值标识符名称for。
回答by Ranga Reddy
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))
}

