How to iterate scala map?
I have scala map:
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开发者_Python百科 iterate over scala map using scala syntactic sugar?
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))
}
精彩评论