Reputation: 395
if i have a map and want to build up a string from iterating over it, is there a way to have the final string be a result of an expression instead of defining a variable and modifying that inside a loop?
instead of this
val myMap = Map("1" -> "2", "3"->"4")
var s = ""
myMap foreach s += ...
i'd rather it be
var s = myMap something ...
Upvotes: 11
Views: 17616
Reputation: 49695
As for Daniel's answer, but with a couple of optimisations and my own formatting preferences:
val myMap = Map("1" -> "2", "3"->"4")
val s = myMap.view map {
case (key, value) => "Key: " + key + "\nValue: " + value
} mkString ("", "\n", "\n")
The optimisations:
view
of the map, I avoid creating an intermediate collectionString.format
Upvotes: 13
Reputation: 4143
This works also fine if you don't bother about your own formatting:
scala> Map("1" -> "2", "3"->"4").mkString(", ")
res6: String = 1 -> 2, 3 -> 4
Upvotes: 2
Reputation: 297155
I'd 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")
)
Upvotes: 18
Reputation: 29011
I'm fairly new to Scala, but you can try reduceLeft
. It goes accumulating a partial value (the string being joined with every element). For example, if you want the keys (or the values) joined in a string, just do:
val s = myMap.keys.reduceLeft( (e, s) => e + s)
This results in "13
"
Upvotes: 2
Reputation: 125119
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
Upvotes: 7