user3663882
user3663882

Reputation: 7357

Transform map to key=value pairs

I have a map: Map[AnyRef, AnyRef]. What is the best way to map it in the following string

"key1=value1 key2=value2 ..."

In Java that's easy. I would just use it

map.entrySet()
    .stream()
    .map(e -> e.getKey().toString() + "=" + e.getValue().toString())
    .collect(joining(" "))

But how to do that in Scala?

Upvotes: 1

Views: 436

Answers (3)

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

map map { case (a, b) =>  s"$a=$b" } mkString " "

. is optional and use string interpolation to make it look good.

Upvotes: 2

talex
talex

Reputation: 20436

map.map{ case (a, b) => a.toString + "=" + b.toString}.mkString(" ")

Upvotes: 2

elm
elm

Reputation: 20405

Using a for comprehension with string interpolation,

(for ((k,v) <- map) yield s"$k=$v").mkString(" ")

Upvotes: 2

Related Questions