How to iterate scala map?

Viewed 69247

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 iterate over scala map using scala syntactic sugar?

3 Answers

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