Muhunthan
Muhunthan

Reputation: 413

Scala - Convert map key value pair to string

I have to convert Map to string with given 2 delimiters and I wanted to use my own delimiter

I have done with the below code

Map("ss"-> "yy", "aa"-> "bb").map(data => s"${data._1}:${data._2}").mkString("|")

The out out is ss:yy|aa:bb

I'm looking for the better way.

Upvotes: 9

Views: 19180

Answers (2)

Shirish Kumar
Shirish Kumar

Reputation: 1532

Map("ss" -> "yy", "aa" -> "bb").map{case (k, v) => k + ":" + v}.mkString("|")

Upvotes: 9

P. Frolov
P. Frolov

Reputation: 876

I believe that mkString is the right way of concatenating strings with delimiters. You can apply it to the tuples as well for uniformity, using productIterator:

Map("ss"-> "yy", "aa"-> "bb")
  .map(_.productIterator.mkString(":"))
  .mkString("|")

Note, however, that productIterator loses type information. In the case of strings that won't cause much harm, but can matter in other situations.

Upvotes: 19

Related Questions