user747980
user747980

Reputation: 395

scala build up string from iterating over map

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

Answers (5)

Kevin Wright
Kevin Wright

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:

  1. By first creating a view of the map, I avoid creating an intermediate collection
  2. On profiling, direct String concatenation is faster than String.format

Upvotes: 13

Antonin Brettsnajdr
Antonin Brettsnajdr

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

Daniel C. Sobral
Daniel C. Sobral

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

Diego Sevilla
Diego Sevilla

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

Ben James
Ben James

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

Related Questions