How to iterate scala map?

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

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.

Tags:

Scala