praxnet praxnet - 12 days ago 5
Scala Question

How to get comma separated values from List of Maps in Scala?

I have listMap1 variable of type List[Map [String, String]] and I want all values associated with key 'k1' as one string with comma separated values

import fiddle.Fiddle, Fiddle.println
import scalajs.js

@js.annotation.JSExport
object ScalaFiddle {

var m1:Map[String,String] = Map(("k1"->"v1"), ("k2"->"vv1"))
var m2:Map[String,String] = Map(("k1"->"v2"),("k2"->"vv2"))
var m3:Map[String,String] = Map(("k1"->"v3"),("k2"->"vv3"))

var listMap1 = List(m1,m2,m3)
var valList = ?? // need all values assoicated with k1 like --> v1,v2,v3...
}

Lee Lee
Answer

A simple approach would be:

listMap1.flatMap(_.get("k1")).mkString(",")

be warned that this will not work if you're generating CSV data and the associated values contain ,s e.g. Map(("k1" -> "\some, string"))