import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.VoidFunction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* coalesce 算子: 将N个分区 合并为 N-M个分区
* 分区合并(减少),在filter后使用效果更佳,可以有效避免数据倾斜问题
*
*/
public class CoalesceOperator {
public static void main(String[] args){
SparkConf conf = new SparkConf().setMaster("local").setAppName("coalesce");
JavaSparkContext sc = new JavaSparkContext(conf);
List<String> names = Arrays.asList("w1","w2","w3","w4","w5");
JavaRDD<String> nameRdd = sc.parallelize(names,4);
JavaRDD<String> namefristRdd = nameRdd.mapPartitionsWithIndex(new Function2<Integer, Iterator<String>, Iterator<String>>() {
@Override
public Iterator<String> call(Integer index, Iterator<String> iterator) throws Exception {
List<String> list = new ArrayList<>();
while (iterator.hasNext()){
list.add("1["+index+"]:"+iterator.next());
}
return list.iterator();
}
},true);
// 将 4 个partition减少为2个partition
JavaRDD<String> tempRdd = namefristRdd.coalesce(2);
JavaRDD<String> result = tempRdd.mapPartitionsWithIndex(new Function2<Integer, Iterator<String>, Iterator<String>>() {
@Override
public Iterator<String> call(Integer index, Iterator<String> iterator) throws Exception {
List<String> list = new ArrayList<>();
while (iterator.hasNext()){
list.add("2["+index+"]:"+iterator.next());
}
return list.iterator();
}
},false);
result.foreach(new VoidFunction<String>() {
@Override
public void call(String s) throws Exception {
System.err.println(s);
}
});
}
}
微信扫描下图二维码加入博主知识星球,获取更多大数据、人工智能、算法等免费学习资料哦!