Thomas L. Thomas L. - 3 years ago 261
Scala Question

How to export multiple maps to csv in Scala?

How can I export all these maps to a single csv file using scala? mapKey contains all keys from all the maps, but not all of the (language) maps may have a value for a certain key.
The head row should contain "key", "default", "de", "fr", "it", "en"

val mapDefault: Map[String, String] = messages.getOrElse("default",Map())

val mapDe: Map[String, String] = messages.getOrElse("de", Map())

val mapFr: Map[String, String] = messages.getOrElse("fr", Map())

val mapEn: Map[String, String] = messages.getOrElse("en", Map())

val mapIt: Map[String, String] = messages.getOrElse("it", Map())

var mapKey: Set[String] = mapDefault.keySet ++ mapDe.keySet ++
mapFr.keySet ++ mapEn.keySet ++ mapIt.keySet

Answer Source

As mentioned in comment - it's best to use some library that constructs the CSV for you, especially to deal with special characters (comma or newline) in input (which would break your CSV if you're not careful).

Either way - you first have to transform your data into a sequence of records with a constant order and number of columns.

Below is an implementation that does not use any library, just to show the gist of how it's done in Scala - feel free to replace the actual CSV creation with a proper library:

// create headers row:
val headers = Seq("key", "default", "de", "fr", "it", "en")

// data rows: for each key in mapKey, create a Seq[String] with the values for this 
// key (in correct order - matching the headers), or with empty String for 
// missing values
val records: Seq[Seq[String]] = => Seq(
  mapDefault.getOrElse(key, ""),
  mapDe.getOrElse(key, ""),
  mapFr.getOrElse(key, ""),
  mapIt.getOrElse(key, ""),
  mapEn.getOrElse(key, "")

// add the headers as the first record
val allRows: Seq[Seq[String]] = headers +: records

// create CSV (naive implementation - assumes no special chars in input!)
val csv: String =",")).mkString("\n")

// write to file:
new PrintWriter("filename.csv") { write(csv); close() }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download