【Spark学习笔记】4、Java版-算子系列之flatMap(f:T => Seq[U]) : RDD[T] => RDD[U]

本文深入探讨了Spark中flatMap操作符的实现原理与应用。通过源码分析,解释了flatMap如何将输入数据集的每个元素转换为多个输出元素,并通过示例展示了其在数据处理中的灵活性与强大功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

flatMap源码

/**
 *  Return a new RDD by first applying a function to all elements of this
 *  RDD, and then flattening the results.
 */
def flatMap[U: ClassTag](f: T => TraversableOnce[U]): RDD[U] = withScope {
  val cleanF = sc.clean(f)
  new MapPartitionsRDD[U, T](this, (context, pid, iter) => iter.flatMap(cleanF))
}

demo

public class FlatMapOperator {

	public static void main(String[] args) {
		SparkConf conf = new SparkConf().setAppName("FlatMapOperator").setMaster("local");
		JavaSparkContext sc = new JavaSparkContext(conf);

		/**
		 * Similar to map, but each input item can be mapped to 0 or more output items (so func should return a Seq rather than a single item).
		 * 
		 */
		List<String> lineList = Arrays.asList("hello hadoop", "hello hdfs", "hello mapreduce", "hello spark");
		JavaRDD<String> lines = sc.parallelize(lineList);

		JavaRDD<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
			private static final long serialVersionUID = 1L;

			@Override
			public Iterable<String> call(String line) throws Exception {
				return Arrays.asList(line.split(" "));
			}
		});
		words.foreach(new VoidFunction<String>() {
			private static final long serialVersionUID = 1L;

			@Override
			public void call(String word) throws Exception {
				System.out.println(word);
			}
		});

		sc.close();
	}

}

输出

hello
hadoop
hello
hdfs
hello
mapreduce
hello
spark

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值