【问题标题】:How to calculate sum list and tuple using RDD Spark如何使用 RDD Spark 计算总和列表和元组
【发布时间】:2021-02-26 06:06:07
【问题描述】:

我有一个看起来像这样的 RDD

val elements = List((8, 12), (9, 10), (5, 16))

输出应该是这样的

result_1 = 22 #sum of the first element
result_2 = 38 #sum of the second element

【问题讨论】:

    标签: scala apache-spark sum tuples rdd


    【解决方案1】:

    有几种方法可以计算总和。

    val result1 = rdd.map(_._1).sum()
    val result2 = rdd.map(_._2).sum()
    
    val result = rdd.reduce((a, b) => (a._1 + b._1, a._2 + b._2))
    
    // result1: Double = 22.0
    // result2: Double = 38.0
    // result: (Int, Int) = (22,38)
    

    【讨论】:

      【解决方案2】:

      你也可以使用fold ;

      rdd.fold(0,0)((first,second) =>(first._1 + second._1, first._2 + second._2)))
      

      用于解释折叠功能;

      https://www.geeksforgeeks.org/scala-reduce-fold-or-scan/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-10
        • 1970-01-01
        • 2016-07-23
        • 2016-06-03
        • 2017-05-25
        • 1970-01-01
        相关资源
        最近更新 更多