Scala - convert map key value to string

I need to convert the map to a 2 delimited data string and I wanted to use my own delimiter

I did with the below code

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

      

Output: ss: yy | aa: bb

I am looking for a better way.

+3


source to share


2 answers


I believe this mkString

is the correct way to concatenate delimited strings. You can apply it to tuples as well for consistency using productIterator

:

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

      



Note that it productIterator

loses type information. In the case of strings that won't do much harm, but might make a difference in other situations.

+8


source


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

      



+1


source







All Articles