user1868607
user1868607

Reputation: 2610

Concatenate two Scala mutable maps preserving the keys of the first map

The scala API let's you append one map to another as follows:

import scala.collection.mutable.{Map => MutableMap}
val m1: MutableMap[Int,String] = MutableMap(1 -> "A", 2 -> "B", 3 -> "C")
val m2: MutableMap[Int,String] = MutableMap(2 -> "X", 3 -> "Y", 4 -> "Z")
m1 ++= m2 // outputs: Map(2 -> X, 4 -> Z, 1 -> A, 3 -> Y)
m1        // outputs: Map(2 -> X, 4 -> Z, 1 -> A, 3 -> Y)

The behaviour is to override the repeated pairs with the pairs coming from the right map.

What is a good way to do it in the opposite way? That is, concatenating the pairs of m1 and m2 in m1 where the pairs of m1 are kept if repeated in m2.

Upvotes: 1

Views: 614

Answers (2)

Dima
Dima

Reputation: 40510

m1 ++= (m2 ++ m1) perhaps? Do you have to mutate m1 (that's rarely the right thing to do in scala anyway)? You could just create a new map as m2 ++ m1 otherwise ...

Upvotes: 2

Lasf
Lasf

Reputation: 2582

Store as a list (or similar collection) and group them:

val l1 = List(1 -> "A", 2 -> "B", 3 -> "C")
val l2 = List(2 -> "X", 3 -> "Y", 4 -> "Z")

(l1 ::: l2).groupBy(_._1) //Map[Int, List[Int, String]]
//output: Map(2 -> List((2,B), (2,X)), 4 -> List((4,Z)), 1 -> List((1,A)), 3 -> List((3,C), (3,Y)))

You can of course remove the leftover integers from the Map's value lists if you want.

Upvotes: 1

Related Questions