RDD算子(十)之PairRDD的Action操作countByKey,collectAsMap

countByKey
将相同key值的数据进行计数
以RDD{(1,2),(2,4),(2,5),(3,4),(3,5),(3,6)}为例,rdd countByKey会返回{(1,1),(2,2),(3,3)}
scala版本

val conf = new SparkConf().setMaster("local[1]").setAppName("CountByKey")
val sc = new SparkContext(conf)
val rdd = sc.parallelize(Array((1,2),(2,4),(2,5),(3,4),(3,5),(3,6)))
val countByKeyRDD = rdd.countByKey()
countByKeyRDD.foreach(println)

在这里插入图片描述

java版本

SparkConf conf = new SparkConf().setMaster("local[1]").setAppName("CountByKey");
JavaSparkContext sc =new JavaSparkContext(conf);
JavaRDD<Tuple2<Integer,Integer>> tupleRDD = sc.parallelize(Arrays.asList(
	new Tuple2<>(1,2),
	new Tup;e2<>(2,4),
	new Tuple2<>(2,5),
	new Tuple2<>(3,4),
	new Tuple2<>(3,5),
	new Tuple2<>(3,6)
));
JavaPairRDD<Integer,Integer> mapRDD = JavaPairRDD.fromJavaRDD(tupleRDD);
Map<Integer,Long> countByKeyRDD = mapRDD.countByKey();
for (Integer i : countByKeyRDD.keySet()) {
	System.out.println("key:\t" + i + "\tvalue:\t" + countByKeyRDD.get(i));
}

在这里插入图片描述

collectAsMap
将pair类型(键值对类型)的RDD转换成map
scala版本

val conf = new SparkConf().setMaster("local[1]").setAppName("CollectAsMap")
val sc = new SparkContext(conf)
val rdd = sc.parallelize(Array((1,2),(2,4),(2,1),(3,4),(3,5),(3,6)))
rdd.collectAsMap().foreach(println)

在这里插入图片描述

java版本

SparkConf conf = new SparkCOnf().setMaster("local[1]").setAppName("CollectAsMap);
JavaSparkContext sc = new JavaSparkContext(conf);
JavaRDD<Tuple2<Integer,Integer>> tupleRDD = sc.parallelize(Arrays.asList(
new Tuple2<>(1,2),
new Tuple2<>(2,4),
new Tuple2<>(2,5),
new Tuple2<>(3,4),
new Tuple2<>(3,5),
new Tuple2<>(3,6)
));
JavaPairRDD<Integer,Integer> pairRdd = tupleRDD.mapToPair(new PairFunction<Tuple2<Integer,Integer>,Integer,Integer>() {
public Tuple2<Integer,Integer> call(Tuple2<Integer,Integer> it) throws Exception {
return it;
}
});
Map<Integer,Integer> collectMap = pairRDD.collectAsMap();
for (Integer i : collectMap.keySet()) {
System.out.println("(" + i + "," + collectMap.get(i) + ")");
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值