11

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 ...
0

5 Answers 5

18

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")
)
Sign up to request clarification or add additional context in comments.

Comments

13

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

Comments

7

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

2 Comments

Potentially a lot of expensive string concatenation there if the map reaches a large size.
That's true. If concatenation is all you're after, use mkString as in Daniel's or Kevin's answer.
2

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"

1 Comment

@Kevin, haha, yes, you're right. I said I was fairly new to Scala :)
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.