Scala折叠元组

时间:2016-09-26 17:06:26

标签: scala dictionary fold

Map(Mary -> List(("Mary", 7065), ("Mary", 2604), ("Mary", 1414))):
  Map[String, List[(String, Int)]]

如何折叠地图以生成类似

的内容
Map("Mary" -> List(("Mary", 7065+2604+1414))):
  Map[String, List[(String, Int)]]

3 个答案:

答案 0 :(得分:1)

对于您的特殊情况,您可以使用此

map.map { case (k, v) => k -> v.map(_._2).sum }

但通常下面的代码适用于所有内容,即使密钥不同

使用元组中的第一项进行groupby,然后折叠列表,该列表是groupby之后的结果映射的值

val list = Map("Mary")
list.groupBy(_._1).map { case (k, v) => v(0)._1 -> v.map(_._2).sum}

Scala REPL

 scala> val list = map("Mary")
 list: List[(String, Int)] = List(("Mary", 7065), ("Mary", 2604), ("Mary", 1414))

 scala> list.groupBy(_._1).map { case (k, v) => v(0)._1 -> v.map(_._2).sum}
 res11: Map[String, Int] = Map("Mary" -> 11083)

 scala> val map =  Map("Mary" -> List(("Mary", 7065), ("Mary", 2604), ("Mary", 1414)))
 map: Map[String, List[(String, Int)]] = Map("Mary" -> List(("Mary", 7065), ("Mary", 2604), ("Mary", 1414)))

 scala> val list = map("Mary")
 list: List[(String, Int)] = List(("Mary", 7065), ("Mary", 2604), ("Mary", 1414))

 scala> list.groupBy(_._1).map { case (k, v) => v(0)._1 -> v.map(_._2).sum}
 res14: Map[String, Int] = Map("Mary" -> 11083)

答案 1 :(得分:0)

您按键分组,然后折叠值:

scala> val input = Map("Mary" -> List(("Mary", 1), ("Mary", 2), ("Mary", 3)))
res1: Iterable[scala.collection.immutable.Map[String,List[(String, Int)]]] = List(Map(Mary -> List((Mary,1), (Mary,2), (Mary,3))))

scala> input.values.map(_.groupBy(_._1).map { case (k, v) => (k -> v.map(_._2).foldLeft(0)(_ + _))})
res7: Iterable[scala.collection.immutable.Map[String,Int]] = List(Map(Mary -> 6))

答案 2 :(得分:0)

val data = Map("Mary" -> List(("Mary", 7065), ("Mary", 2604), ("Mary", 1414)))

data map { case (x,y) => (x, y.foldLeft(0)((acc, elem) => acc + elem._2)) }

这导致地图: scala.collection.immutable.Map[String,Int] = Map(Mary -> 11083)