Search code examples
scaladictionaryjoinmappingscala-collections

Join 3 maps (2 master map, 1 resultant map), to map the composite key in the resultant map to have values from the master maps


I have one map containing some master data(id->description): val map1: Map[String, String] = Map("001" -> "ABCD", "002" -> "MNOP", "003" -> "WXYZ")

I have another map containing some other master data(id->description): val map2: Map[String, String] = Map("100" -> "Ref1", "200" -> "Ref2", "300" -> "Ref3")

I have a resultant map as follows which is derived from some data set which has yieled the following map where the id from map1 and map2's have been used in combination to determine the key, to be precise a map derived from grouping on ids from both the above maps and then accumulating the amounts:

val map3:Map[(String, String),Double] = Map(("001","200")->3452.30,("003","300")->78484.33,("002","777") -> 893.45)

I need an output in a Map as follows: ("ABCD","Ref2")->3452.30,("WXYZ","Ref3")->78484.33,("MNOP","777") -> 893.45)

I have been trying this:

val map5 = map3.map(obj => {
  (map1 getOrElse(obj._1._1, "noMatchMap1"))
  (map2 getOrElse(obj._1._2, "noMatchMap2"))
} match {
  case "noMatchMap1" => obj
  case "noMatchMap2" => obj
  case value => value -> obj._2
})

Solution

  • This should be it :

    map3.map{
        case((key1, key2), d) => ((map1.getOrElse(key1, key1), map2.getOrElse(key2, key2)),d)
      }