EnverOsmanov
EnverOsmanov

Reputation: 655

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", "[email protected]"), ("phone", "ph0997832"))
val query2 = Map(("email", "[email protected]"), ("fax", "fax0997832"))

And I want something like that:

List("email", "phone", "fax")
List(List("[email protected]", "ph0997832", ""), List("[email protected]", "", "fax0997832"))

Upvotes: 1

Views: 83

Answers (1)

Marth
Marth

Reputation: 24802

Using :

scala> val queries = List(query1, query2)
queries: List[Map[String,String]] = List(
                                      Map(email -> [email protected], phone -> ph0997832),
                                      Map(email -> [email protected], 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([email protected], ph0997832, ""),
                                List([email protected], "", fax0997832))

Upvotes: 2

Related Questions