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 Map get() method with exampleThe get() method is utilized to give the value associated with the keys of the map. The values are returned here as an Option i.e, either in form of Some or None. Return Type: It returns the keys corresponding to the values given in the method as argument.
Scala Map foreach() method with exampleThe foreach() method is utilized to apply the given function to all the elements of the map. Return Type: It returns all the elements of the map after applying the given function to each of them. So, the identical elements are taken only once.
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) => ...}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With