scala 按键合并地图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7755214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Merge maps by key
提问by Submonoid
Say I have two maps:
假设我有两张地图:
val a = Map(1 -> "one", 2 -> "two", 3 -> "three")
val b = Map(1 -> "un", 2 -> "deux", 3 -> "trois")
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.
感觉应该有一种很好的、惯用的方式来做到这一点。
采纳答案by Travis Brown
scala.collection.immutable.IntMaphas an intersectionWithmethod that does precisely what you want (I believe):
scala.collection.immutable.IntMap有一种intersectionWith方法可以完全满足您的要求(我相信):
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))
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.
这给你IntMap(1 -> List(one, un), 2 -> List(two, deux), 3 -> List(three, trois))。请注意,它正确地忽略了仅出现在a.
As a side note: I've often found myself wanting the unionWith, intersectionWith, etc. functions from Haskell's Data.Mapin Scala. I don't think there's any principled reason that they should only be available on IntMap, instead of in the base collection.Maptrait.
作为一个方面说明:我经常发现自己想要的unionWith,intersectionWith从等功能Haskell的Data.Map斯卡拉。我认为没有任何原则性的理由表明它们应该只在IntMap,而不是在基本collection.Map特征中可用。
回答by Infinity
val a = Map(1 -> "one", 2 -> "two", 3 -> "three")
val b = Map(1 -> "un", 2 -> "deux", 3 -> "trois")
val c = a.toList ++ b.toList
val d = c.groupBy(_._1).map{case(k, v) => k -> v.map(_._2).toSeq}
//res0: scala.collection.immutable.Map[Int,Seq[java.lang.String]] =
//Map((2,List(two, deux)), (1,List(one, un), (3,List(three, trois)))
回答by Ben James
Scalaz adds a method |+|for any type Afor which a Semigroup[A]is available.
Scalaz|+|为任何AaSemigroup[A]可用的类型添加了一个方法。
If you mapped your Maps so that each value was a single-element sequence, then you could use this quite simply:
如果您映射 Maps 以便每个值都是一个单元素序列,那么您可以非常简单地使用它:
scala> a.mapValues(Seq(_)) |+| b.mapValues(Seq(_))
res3: scala.collection.immutable.Map[Int,Seq[java.lang.String]] = Map(1 -> List(one, un), 2 -> List(two, deux), 3 -> List(three, trois))
回答by user unknown
Here is my first approach before looking for the other solutions:
在寻找其他解决方案之前,这是我的第一种方法:
for (x <- a) yield
x._1 -> Seq (a.get (x._1), b.get (x._1)).flatten
To avoid elements which happen to exist only in a or b, a filter is handy:
为了避免只存在于 a 或 b 中的元素,过滤器很方便:
(for (x <- a) yield
x._1 -> Seq (a.get (x._1), b.get (x._1)).flatten).filter (_._2.size == 2)
Flatten is needed, because b.get (x._1) returns an Option. To make flatten work, the first element has to be an option too, so we can't just use x._2 here.
需要展平,因为 b.get (x._1) 返回一个选项。为了使展平工作,第一个元素也必须是一个选项,所以我们不能在这里只使用 x._2。
For sequences, it works too:
对于序列,它也适用:
scala> val b = Map (1 -> Seq(1, 11, 111), 2 -> Seq(2, 22), 3 -> Seq(33, 333), 5 -> Seq(55, 5, 5555))
b: scala.collection.immutable.Map[Int,Seq[Int]] = Map(1 -> List(1, 11, 111), 2 -> List(2, 22), 3 -> List(33, 333), 5 -> List(55, 5, 5555))
scala> val a = Map (1 -> Seq(1, 101), 2 -> Seq(2, 212, 222), 3 -> Seq (3, 3443), 4 -> (44, 4, 41214))
a: scala.collection.immutable.Map[Int,ScalaObject with Equals] = Map(1 -> List(1, 101), 2 -> List(2, 212, 222), 3 -> List(3, 3443), 4 -> (44,4,41214))
scala> (for (x <- a) yield x._1 -> Seq (a.get (x._1), b.get (x._1)).flatten).filter (_._2.size == 2)
res85: scala.collection.immutable.Map[Int,Seq[ScalaObject with Equals]] = Map(1 -> List(List(1, 101), List(1, 11, 111)), 2 -> List(List(2, 212, 222), List(2, 22)), 3 -> List(List(3, 3443), List(33, 333)))
回答by Guillaume Massé
val fr = Map(1 -> "one", 2 -> "two", 3 -> "three")
val en = Map(1 -> "un", 2 -> "deux", 3 -> "trois")
def innerJoin[K, A, B](m1: Map[K, A], m2: Map[K, B]): Map[K, (A, B)] = {
m1.flatMap{ case (k, a) =>
m2.get(k).map(b => Map((k, (a, b)))).getOrElse(Map.empty[K, (A, B)])
}
}
innerJoin(fr, en) // Map(1 -> ("one", "un"), 2 -> ("two", "deux"), 3 -> ("three", "trois")): Map[Int, (String, String)]
回答by Xavier Guihot
Starting Scala 2.13, you can use groupMapwhich (as its name suggests) is an equivalent of a groupByfollowed by mapon values:
从 开始Scala 2.13,您可以使用groupMapwhich(顾名思义)相当于 agroupBy后跟mapon 值:
// 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,map2is implicitlyconverted toSeqto align withmap1.toSeq's type - but you could choose to make it explicit by usingmap2.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)
将两个映射连接为一个元组序列 (
List((1, "one"), (2, "two"), (3, "three")))。为了简洁,map2被隐式转换成Seq要对齐map1.toSeq的类型-但你可以选择,使其明确使用map2.toSeq。groups 元素基于它们的第一个元组部分 (_._1) (组Map 的组部分)maps 将值分组到它们的第二个元组部分 (_._2) (组Map 的映射部分)
回答by Submonoid
So I wasn't quite happy with either solution (I want to build a new type, so semigroup doesn't really feel appropriate, and Infinity's solution seemed quite complex), so I've gone with this for the moment. I'd be happy to see it improved:
所以我对这两种解决方案都不太满意(我想构建一个新类型,所以半群并不真正合适,Infinity 的解决方案看起来很复杂),所以我暂时采用了这个。我很高兴看到它有所改进:
def merge[A,B,C](a : Map[A,B], b : Map[A,B])(c : (B,B) => C) = {
for (
key <- (a.keySet ++ b.keySet);
aval <- a.get(key); bval <- b.get(key)
) yield c(aval, bval)
}
merge(a,b){Seq(_,_)}
I wanted the behaviour of returning nothing when a key wasn't present in either map (which differs from other solutions), but a way of specifying this would be nice.
我希望当任一映射中都不存在键时不返回任何内容(这与其他解决方案不同),但是指定这种方式的方法会很好。
回答by Aslanbek Aylarov
def merge[A,B,C,D](b : Map[A,B], c : Map[A,C])(d : (Option[B],Option[C]) => D): Map[A,D] = {
(b.keySet ++ c.keySet).map(k => k -> d(b.get(k), c.get(k))).toMap
}
def optionSeqBiFunctionK[A]:(Option[A], Option[A]) => Seq[A] = _.toSeq ++ _.toSeq
merge(a,b)(optionSeqBiFunctionK)

