如何从Spark中的多个值计算平均值

How to calculate average from multiple values in Spark

我有一个映射器发出 key/value 对(复合键和复合值用逗号分隔)。

例如

键: a,b,c,d 值: 1,2,3,4,5

键: a1,b1,c1,d1 值: 5,4,3,2,1

...

...

键: a,b,c,d 值: 5,4,3,2,1

我可以使用 reduceByKey 轻松地对这些值求和。

例如

reduceByKey(new Function2<String, String, String>() {

        @Override
        public String call(String value1, String value2) {
            String oldValue[] = value1.toString().split(",");
            String newValue[] = value2.toString().split(",");

            int iFirst = Integer.parseInt(oldValue[0]) + Integer.parseInt(newValue[0]);
            int iSecond = Integer.parseInt(oldValue[1]) + Integer.parseInt(newValue[1]);
            int iThird = Integer.parseInt(oldValue[2]) + Integer.parseInt(newValue[2]);
            int iFourth = Integer.parseInt(oldValue[3]) + Integer.parseInt(newValue[3]);
            int iFifth = Integer.parseInt(oldValue[4]) + Integer.parseInt(newValue[4]);

            return iFirst  + "," + iSecond + ","
                    + iThird+ "," + iFourth+ "," + iFifth;

        }
    });

但问题是我如何找到其中一个值的平均值。假设我想对 iFirst、iSecond、iThird 和 iFourth 求和,但我想求 iFifth 的平均值。我该怎么做?通过简单的 key/value 对,我可以使用 mapValues 函数,但不确定如何使用我的示例来实现。请指教

我已经使用 foldByKey 功能解决了这个问题。