How to iterate scala map?

Scala

Scala Problem Overview


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?

Scala Solutions


Solution 1 - Scala

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.

Solution 2 - Scala

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

Solution 3 - Scala

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaceView Question on Stackoverflow
Solution 1 - ScalaRex KerrView Answer on Stackoverflow
Solution 2 - ScalatenshiView Answer on Stackoverflow
Solution 3 - ScalaRanga ReddyView Answer on Stackoverflow