EnverOsmanov EnverOsmanov - 4 months ago 23
Scala Question

Merge different Map by keys

How I can merge in short way two maps by their keys but they could have different keys.
For example I have

val query1 = Map(("email", "aa@ya.ru"), ("phone", "ph0997832"))
val query2 = Map(("email", "bb@ya.ru"), ("fax", "fax0997832"))

And I want something like that:

List("email", "phone", "fax")
List(List("aa@ya.ru", "ph0997832", ""), List("bb@ya.ru", "", "fax0997832"))


Using :

scala> val queries = List(query1, query2)
queries: List[Map[String,String]] = List(
                                      Map(email -> aa@ya.ru, phone -> ph0997832),
                                      Map(email -> bb@ya.ru, fax -> fax0997832)

Getting the keys is easy enough; call .keys on every Map, flatten the result and remove the duplicates :

scala> val keys = queries.flatMap(_.keys).distinct
keys: List[String] = List(email, phone, fax)

Getting the second list; fetch the value of all keys for queries, using .getOrElse(k, "") to get an empty string instead of a None :

scala> queries.map(q => keys.map(k => q.getOrElse(k, "")))
res0: List[List[String]] = List(List(aa@ya.ru, ph0997832, ""),
                                List(bb@ya.ru, "", fax0997832))