foldByKey
函数原型:
def foldByKey(zeroValue: V)(func: (V, V) => V): RDD[(K, V)]
def foldByKey(zeroValue: V, numPartitions: Int)(func: (V, V) => V): RDD[(K, V)]
def foldByKey(zeroValue: V, partitioner: Partitioner)(func: (V, V) => V): RDD[(K, V)]
作用:将RDD[K,V]根据K将V做折叠、合并处理,zeroValue作为初始参数,调用func得到V,
再根据Key按照func对V进行调用。
例子:
scala> var rdd1 = sc.makeRDD(Array(("A",0),("A",2),("B",1),("B",2)))
rdd1: org.apache.spark.rdd.RDD[(String, Int)] = ParallelCollectionRDD[7] at makeRDD at <console>:27
scala> rdd1.foldByKey(0)(_+_).collect
res3: Array[(String, Int)] = Array((A,2), (B,3))
说明: 将0应用到_+_上,Array(("A",0+0),("A",2+0)) 再进一步处理得到Array(("A",0+2))最终得到Array(("A",2))