Scala如何对元组列表的字段进行求和?

时间:2015-08-23 02:19:29

标签: json scala

我希望通过对y字段求和来减少具有x等公共字段的元组列表。

输入:

List(("x" -> "foo", "y" -> 1000),
     ("x" -> "foo", "y" -> 1),
     ("x" -> "bar", "y" -> 101))

输出:

List(("x" -> "foo", "y" -> 1001),
     ("x" -> "bar", "y" -> 101))

有什么好处? foldLeft还是reduce?

1 个答案:

答案 0 :(得分:1)

你的项目应该是元组:

List(("x" -> "foo", "y" -> 1000),("x" -> "foo", "y" -> 1), ("x" -> "bar", "y" -> 101))

使用groupBy对您的密钥进行分组,并mapValues生成目标:

List(("x" -> "foo", "y" -> 1000),("x" -> "foo", "y" -> 1), ("x" -> "bar", "y" -> 101))
 .groupBy(x => x._1)
 .mapValues(t => t.head._2._1 -> t.foldLeft(0.0)(_ + _._2._2))

输出

scala.collection.immutable.Map[(String, String),(String, Double)] = 
    Map((x,foo) -> (y,1001.0), (x,bar) -> (y,101.0))