Merge maps by key

前端 未结 8 2143
不思量自难忘°
不思量自难忘° 2020-12-01 05:14

Say I have two maps:

val a = Map(1 -> \"one\", 2 -> \"two\", 3 -> \"three\")
val b = Map(1 -> \"un\", 2 -> \"deux\", 3 -> \"trois\")
         


        
8条回答
  •  猫巷女王i
    2020-12-01 05:54

    Starting Scala 2.13, you can use groupMap which (as its name suggests) is an equivalent of a groupBy followed by map on values:

    // val map1 = Map(1 -> "one", 2 -> "two",  3 -> "three")
    // val map2 = Map(1 -> "un",  2 -> "deux", 3 -> "trois")
    (map1.toSeq ++ map2).groupMap(_._1)(_._2)
    // Map(1 -> List("one", "un"), 2 -> List("two", "deux"), 3 -> List("three", "trois"))
    

    This:

    • Concatenates the two maps as a sequence of tuples (List((1, "one"), (2, "two"), (3, "three"))). For conciseness, map2 is implicitly converted to Seq to align with map1.toSeq's type - but you could choose to make it explicit by using map2.toSeq.

    • groups elements based on their first tuple part (_._1) (group part of groupMap)

    • maps grouped values to their second tuple part (_._2) (map part of groupMap)

提交回复
热议问题