本篇内容主要讲解“spark中flatmap跟map的区别”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“spark中flatmap跟map的区别”吧!
背景
map和flatmap扁平化调用,从字面意思或者官网介绍,可能会给一些人在理解上造成困扰【包括本人】,所以今天专门花时间来分析,现整理如下:
首先做一下名词解释------------------------------------------------
我的理解
map:map方法返回的是一个object,map将流中的当前元素替换为此返回值;
flatMap:flatMap方法返回的是一个stream,flatMap将流中的当前元素替换为此返回流拆解的流元素,底层是递归性质的只要数据是集合就会把该集合全部数据拿出来;
官方解释
map:Returns a stream consisting of the results of applying the given function to the elements of this stream.
返回一个流,包含给定函数应用在流中每一个元素后的结果
flatmap:Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.
返回一个流,包含将此流中的每个元素替换为通过给定函数映射应用于每个元素而生成的映射流的内容
举例说明
有二箱鸡蛋,每箱5个,现在要把鸡蛋加工成煎蛋,然后分给学生。
map做的事情:把二箱鸡蛋分别加工成煎蛋,还是放成原来的两箱,分给2组学生;
flatMap做的事情:把二箱鸡蛋分别加工成煎蛋,然后放到一起【10个煎蛋】,分给10个学生;
完整测试代码如下:
public class Map_FlatMap {
List<String[]> eggs = new ArrayList<>();
@Before
public void init() {
// 第一箱鸡蛋
eggs.add(new String[]{"鸡蛋_1", "鸡蛋_1", "鸡蛋_1", "鸡蛋_1", "鸡蛋_1"});
// 第二箱鸡蛋
eggs.add(new String[]{"鸡蛋_2", "鸡蛋_2", "鸡蛋_2", "鸡蛋_2", "鸡蛋_2"});
}
// 自增生成组编号
static int group = 1;
// 自增生成学生编号
static int student = 1;
/**
* 把二箱鸡蛋分别加工成煎蛋,还是放在原来的两箱,分给2组学生
*/
@Test
public void map() {
eggs.stream()
.map(x -> Arrays.stream(x).map(y -> y.replace("鸡", "煎")))
.forEach(x -> System.out.println("组" + group++ + ":" + Arrays.toString(x.toArray())));
/*
控制台打印:------------
组1:[煎蛋_1, 煎蛋_1, 煎蛋_1, 煎蛋_1, 煎蛋_1]
组2:[煎蛋_2, 煎蛋_2, 煎蛋_2, 煎蛋_2, 煎蛋_2]
*/
}
/**
* 把二箱鸡蛋分别加工成煎蛋,然后放到一起【10个煎蛋】,分给10个学生
*/
@Test
public void flatMap() {
eggs.stream()
.flatMap(x -> Arrays.stream(x).map(y -> y.replace("鸡", "煎")))
.forEach(x -> System.out.println("学生" + student++ + ":" + x));
/*
控制台打印:------------
学生1:煎蛋_1
学生2:煎蛋_1
学生3:煎蛋_1
学生4:煎蛋_1
学生5:煎蛋_1
学生6:煎蛋_2
学生7:煎蛋_2
学生8:煎蛋_2
学生9:煎蛋_2
学生10:煎蛋_2
*/
}
}
落实到Python中区别就是
flatMap
val lineArray = Array("hello you","hello me","hello world")
val lines = sc.parallelize(lineArray, 1)
val words = lines.flatMap(line =>{ line.split(" ") })
words.foreach {
word => println(word.mkString)
}
结果:
map
val lineArray = Array("hello you","hello me","hello world")
val lines = sc.parallelize(lineArray, 1)
val words = lines.map(line =>{ line.split(" ") })
words.foreach {
word => println(word.mkString)
}
结果
map:获取一个新元素(原本几个元素还是几个元素)
flatmap: 获取一个或者多个新元素(比原来的元素多)
到此,相信大家对“spark中flatmap跟map的区别”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/4511602/blog/4825177