减少元组的可变数量在Scala中映射[Key,List [Value]]的序列

时间:2014-10-22 20:26:09

标签: scala map tuples seq

我有两个序列:

Seq("a" -> 1, "b" -> 2)
Seq("a" -> 3, "b" -> 4)

我想要的是一个如下所示的结果Map:

Map(a -> List(3, 1), b -> List(4, 2))

3 个答案:

答案 0 :(得分:7)

val s1 = Seq("a" -> 1, "b" -> 2)
val s2 = Seq("a" -> 3, "b" -> 4)

val ss = s1 ++ s2

val toMap = ss.groupBy(x => x._1).map { case (k,v) => (k,  v.map(_._2))}

res0: scala.collection.immutable.Map[String,Seq[Int]] = Map(b -> List(2, 4), a -> List(1, 3))

你可以对这个或你想要的东西进行排序。

答案 1 :(得分:1)

你可以尝试

scala> val seq = Seq("a" -> 1, "b" -> 2) ++ Seq("a" -> 3, "b" -> 4)
seq: Seq[(String, Int)] = List((a,1), (b,2), (a,3), (b,4))

scala> seq groupBy(_._1) mapValues(_ map(_._2))
res9: scala.collection.immutable.Map[String,Seq[Int]] = Map(b -> List(2, 4), a -> List(1, 3))

答案 2 :(得分:0)

def reduceToMap[K, V](seqs: Seq[(K, V)]*): Map[K, List[V]] = {
    seqs.reduce(_ ++ _).foldLeft(Map.empty[K, List[V]])((memo, next) =>
      memo.get(next._1) match {
        case None     => memo.updated(next._1, next._2 :: Nil)
        case Some(xs) => memo.updated(next._1, next._2 :: xs)
      }
    )
  }


scala> reduceToMap(Seq("a" -> 1, "b" -> 2), Seq("a" -> 3, "b" -> 4))
res0: Map[String,List[Int]] = Map(a -> List(3, 1), b -> List(4, 2))

scala> reduceToMap(Seq.empty)
res1: Map[Nothing,List[Nothing]] = Map()