Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate scala map?

Tags:

scala

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?

like image 473
ace Avatar asked Jun 15 '11 21:06

ace


People also ask

How do I read a Scala map?

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.

How do you write a foreach in Scala?

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.


2 Answers

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.

like image 140
Rex Kerr Avatar answered Sep 25 '22 07:09

Rex Kerr


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) => ...} 
like image 25
tenshi Avatar answered Sep 21 '22 07:09

tenshi