8
votes

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.

2
You could destructure your key-value pairs in the function passed to map, for better readability: map { case (key, value) => s"$key:$value" } - jub0bs
Thanks for your comments I'm looking the better answer specially for s"$key:$value" part - Muhunthan
Define "better"... - jub0bs
Using any map library function with out string concatenation like .mkString - Muhunthan
I don't know if it is any better, but alternative approach would be: myMap.map(x => x.productIterator.mkString(":")).mkString("|") - Akavall

2 Answers

18
votes

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.

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