Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - Convert map key value pair to string

Tags:

scala

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.

like image 599
Muhunthan Avatar asked Apr 28 '17 04:04

Muhunthan


2 Answers

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.

like image 156
P. Frolov Avatar answered Sep 28 '22 00:09

P. Frolov


Map("ss" -> "yy", "aa" -> "bb").map{case (k, v) => k + ":" + v}.mkString("|")
like image 44
Shirish Kumar Avatar answered Sep 28 '22 01:09

Shirish Kumar