Reputation: 67
I have a Map[String,Seq[Any]], and I want to serialize it to a CSV file.
example:
Map("k1"-> List(1,2,3),"k2"->List ("toto","fofo","popo"))
to
k1,k2
1,toto
2,fofo
3,popo
any suggestions ??
Upvotes: 1
Views: 549
Reputation: 3519
Something like this can be a start:
val m : Map[String, Seq[Any]] = Map("k1"-> Seq(1,2,3),"k2"->Seq("toto","fofo","popo"))
val file = new File("/path/to/output/file")
val pw = new PrintWriter(new FileWriter(file))
val header = m.keys.toList
val numLines = m(header.head).get.size
pw.println(header.mkString(","))
(0 until numLines).foreach(n => {
val line = header.map(k => m(k)(n)).mkString(",")
pw.println(line)
})
pw.close()
EDIT: I had misunderstood the question and the original answer was wrong. For another approach see LuisMiguelMejíaSuárez's link.
Upvotes: 2
Reputation: 505
To solve this problem, i would define a method like below if I don't have control on the lists sizes :
def zipNestedLists[A](lists: List[List[A]]): List[List[Any]] = lists match {
case Nil => Nil
case Nil :: _ => Nil
case _ => lists.map(_.head) :: zipNestedLists(lists.map(_.tail))
}
if I'm sure that all lists have the same size, then in this case i would use transpose
:
scala> List(List(a1,a2,a3,a4), List(b1,b2,b3,b4), List(c1,c2,c3,c4)).transpose
List(List(a1,b1,c1),List(a2,b2,c2),List(a3,b3,c3),List(a4,b4,c4))
please see https://www.scala-lang.org/api/current/scala/collection/immutable/List.html#transpose for more infos on transpose
.
Then construct the header :
val header: String = map.keySet.mkString(",")
After that, the body :
val body = zipNestedLists(map.values.toList)
then output to the file (thanks @jrook)
val file = new File("path")
val pw = new PrintWriter(new FileWriter(file))
pw.println(header)
body.foreach(v => pw.println(v.mkString(",")))
pw.close()
Please note that the method zipNestedLists
will fail for empty lists. Filter non empty lists before calling it.
Upvotes: 2