Scala create string from map iteration

If I have a map and you want to create a line from iterating over it, is there a way for the final line to be the result of an expression instead of defining a variable and changing inside the loop?

instead of this

val myMap = Map("1" -> "2", "3"->"4") var s = "" myMap foreach s += ... 

I would prefer it

 var s = myMap something ... 
+8
scala
source share
5 answers

You can do this with a fold:

 scala> myMap.foldLeft("") { (s: String, pair: (String, String)) => | s + pair._1 + pair._2 | } res0: java.lang.String = 1234 
+6
source share

I would just map and mkString . For example:

 val s = ( Map("1" -> "2", "3"->"4") map { case (key, value) => "Key: %s\nValue: %s" format (key, value) } mkString ("", "\n", "\n") ) 
+17
source share

Regarding Daniel's answer, but with a few optimizations and my formatting preferences:

 val myMap = Map("1" -> "2", "3"->"4") val s = myMap.view map { case (key, value) => "Key: " + key + "\nValue: " + value } mkString ("", "\n", "\n") 

Optimization:

  • By first creating a view on a map, I avoid creating an intermediate collection
  • When profiling, direct string concatenation is faster than String.format
+13
source share

I'm new to Scala, but you can try reduceLeft . It accumulates a partial value (a string connects to each element). For example, if you want the keys (or values) to be combined into a string, simply do:

 val s = myMap.keys.reduceLeft( (e, s) => e + s) 

The result is " 13 "

+2
source share

This works fine if you are not worried about your own formatting:

 scala> Map("1" -> "2", "3"->"4").mkString(", ") res6: String = 1 -> 2, 3 -> 4 
+2
source share

All Articles