0

I have 2 Maps :

val map1 = Map("col_1" -> "data_1", "col_2" -> "data_2", "col_3" -> "data_3")
val map2 = Map("col_1" -> "myval_1", "col_2" -> "myval_2", "col_3" -> "myval_3")

Required Output:

res = Map("col_1" -> ("data_1", "myval_1"), "col_2" -> ("data_2", "myval_2"),
"col_2" -> ("data_2", "myval_2") )

Basically Keeping the keys of 'map1' & merging values of both maps Output must be Tuple and not a List or Seq

AJm
  • 993
  • 2
  • 20
  • 39

3 Answers3

7

Use map (throws if one of keys is missing on the other map):

val res = map1.map { case (k, v) => (k, (v, map2(k))) }

Or use collect (skips the keys not present in both maps):

val res = map1.collect { case (k, v) if map2.contains(k) => (k, (v, map2(k))) }

Or with default value for map2:

val res = map1.map { case (k, v) => (k, (v, map2.getOrElse(k, ""))) }

For symmetric case, I'd go with Scalaz version from my other answer

Oleg Pyzhcov
  • 7,323
  • 1
  • 18
  • 30
0

This is a simple solution you can apply in your case

val resultMap = map1.map(kv => {
      if(map2(kv._1) != None){
        kv._1 -> (kv._2, map2(kv._1))
      }
      else{
        kv
      }
    })

resultMap should be

Map(col_1 -> (data_1,myval_1), col_2 -> (data_2,myval_2), col_3 -> (data_3,myval_3))

Above case fails when there is no key of map1 in map2, for that case you can use match case as following

val resultMap = map1.map(kv => map2 getOrElse(kv._1, "noKey") match{
  case "noKey" => kv
  case x => kv._1 -> (kv._2, x)
})
Ramesh Maharjan
  • 41,071
  • 6
  • 69
  • 97
0

Get all the keys which present in map1 along with the combination which keys present in map2 :

val res = map1.collect { case (k, v) => if (map2.contains(k)) (k, (v, map2(k))) else (k, (v, "")) }
Learner
  • 1,170
  • 11
  • 21