按键合并地图 [英] Merge maps by key
问题描述
说我有两张地图:
val a = Map(1 -> "one", 2 -> "two", 3 -> "three")
val b = Map(1 -> "un", 2 -> "deux", 3 -> "trois")
我想通过键合并这些映射,应用一些函数来收集值(在这种情况下,我想将它们收集到seq中,给出:
I want to merge these maps by key, applying some function to collect the values (in this particular case I want to collect them into a seq, giving:
val c = Map(1 -> Seq("one", "un"), 2 -> Seq("two", "deux"), 3 -> Seq("three", "trois"))
感觉应该有一种很好的习惯用法.
It feels like there should be a nice, idiomatic way of doing this.
推荐答案
scala.collection.immutable.IntMap
有一个intersectionWith
方法可以精确地执行您想要的操作(我相信):
scala.collection.immutable.IntMap
has an intersectionWith
method that does precisely what you want (I believe):
import scala.collection.immutable.IntMap
val a = IntMap(1 -> "one", 2 -> "two", 3 -> "three", 4 -> "four")
val b = IntMap(1 -> "un", 2 -> "deux", 3 -> "trois")
val merged = a.intersectionWith(b, (_, av, bv: String) => Seq(av, bv))
这给您IntMap(1 -> List(one, un), 2 -> List(two, deux), 3 -> List(three, trois))
.请注意,它会正确忽略仅在a
中出现的密钥.
This gives you IntMap(1 -> List(one, un), 2 -> List(two, deux), 3 -> List(three, trois))
. Note that it correctly ignores the key that only occurs in a
.
作为旁注:我经常发现自己想要来自intersectionWith
等功能. .2.0/doc/html/Data-Map.html> Scala中Haskell的Data.Map
.我不认为有任何原则上的理由只能在IntMap
上使用它们,而不是在基本的collection.Map
特性上使用.
As a side note: I've often found myself wanting the unionWith
, intersectionWith
, etc. functions from Haskell's Data.Map
in Scala. I don't think there's any principled reason that they should only be available on IntMap
, instead of in the base collection.Map
trait.
这篇关于按键合并地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!