Search code examples
scaladictionarymergekeyseq

Scala : Merge two immutable maps on key and get new immutable map with same type


I want to merge two immutable maps on same key of below type:

scala.collection.immutable.HashMap[String,Seq[String]]

and return type should also be same: scala.collection.immutable.HashMap[String,Seq[String]]

for example:

scala> map2
res17: scala.collection.immutable.HashMap[String,Seq[String]] = Map(key1 -> List(value1-2), key2 -> List(value2))

scala> map3
res18: scala.collection.immutable.HashMap[String,Seq[String]] = Map(key1 -> List(value1-3), key3 -> List(value3))


merging above two map should be output to:

Map(key1->List(value1-2,value1-3), key2->List(value2), key3->List(value3))

Note : Returned map should have a Seq of String as a value not Seq of Seq of String


Solution

  • You can merge two maps like this :

    map2 ++ map3.map{ case (k,v) => k -> (v ++ map2.getOrElse(k,Nil)) }
    

    Because ++ operator is immutable, a new Map will be created.