138、Spark核心编程进阶之mapPartitions以及学生成绩查询案例

mapPartitions,类似map,不同之处在于,map算子,一次就处理一个partition中的一条数据,mapPartitions算子,一次处理一个partition中所有的数据

推荐的使用场景
如果你的RDD的数据量不是特别大,那么建议采用mapPartitions算子替代map算子,可以加快处理速度
但是如果你的RDD的数据量特别大,比如说10亿,不建议用mapPartitions,可能会内存溢出

public class MapPartitions {
    public static void main(String[] args) {

        SparkConf conf = new SparkConf().setAppName("MapPartitionsJava").setMaster("local");

        JavaSparkContext sparkContext = new JavaSparkContext(conf);
        // 准备一下模拟数据
        List<String> studentNames = Arrays.asList("张三", "李四", "王二", "麻子");

        JavaRDD<String> studentNamesRDD = sparkContext.parallelize(studentNames, 2);


        final Map<String, Double> studentScoreMap = new HashMap<String, Double>();
        studentScoreMap.put("张三", 278.5);
        studentScoreMap.put("李四", 290.0);
        studentScoreMap.put("王二", 301.0);
        studentScoreMap.put("麻子", 205.0);

        JavaRDD<Double> scoreRDD = studentNamesRDD.mapPartitions(new FlatMapFunction<Iterator<String>, Double>() {
            @Override
            public Iterator<Double> call(Iterator<String> stringIterator) throws Exception {
                // 因为算子一次处理一个partition的所有数据
                // call函数接收的参数,是iterator类型,代表了partition中所有数据的迭代器
                // 返回的是一个iterable类型,代表了返回多条记录,通常使用List类型

                List<Double> scores = new ArrayList<Double>();

                while (stringIterator.hasNext()) {
                    String studentName = stringIterator.next();
                    Double score = studentScoreMap.get(studentName);
                    scores.add(score);
                }
                return scores.iterator();
            }
        });

        scoreRDD.foreach(new VoidFunction<Double>() {
            @Override
            public void call(Double aDouble) throws Exception {
                System.out.println("aDouble = " + aDouble);
            }
        });
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值