与map方法类似,map是对rdd中的每一个元素进行操作,而mapPartitions(foreachPartition)则是对rdd中的每个分区的迭代器进行操作。如果在map过程中需要频繁创建额外的对象(例如将rdd中的数据通过jdbc写入数据库,map需要为每个元素创建一个链接而mapPartition为每个partition创建一个链接),则mapPartitions效率比map高的多。

SparkSql或DataFrame默认会对程序进行mapPartition的优化。

Demo

实现将每个数字变成原来的2倍的功能

比如:输入2,结果(2,4)

使用map

val a = sc.parallelize(1 to 9, 3)
def mapDoubleFunc(a : Int) : (Int,Int) = {
(a,a*2)
}
val mapResult = a.map(mapDoubleFunc) println(mapResult.collect().mkString)

结果

(1,2)(2,4)(3,6)(4,8)(5,10)(6,12)(7,14)(8,16)(9,18)

使用mapPartitions

val a = sc.parallelize(1 to 9, 3)
def doubleFunc(iter: Iterator[Int]) : Iterator[(Int,Int)] = {
var res = List[(Int,Int)]()
while (iter.hasNext)
{
val cur = iter.next;
res .::= (cur,cur*2)
}
res.iterator
}
val result = a.mapPartitions(doubleFunc)
println(result.collect().mkString)

结果

(3,6)(2,4)(1,2)(6,12)(5,10)(4,8)(9,18)(8,16)(7,14)

最新文章

  1. Centos7 修改ssh 默认端口号
  2. 组合or继承
  3. IO流-概览
  4. 打开网页自动弹出qq客户端
  5. vc6静态库的生成和调用
  6. Python进阶之闭包
  7. Cacti+Nagios监控平台完美整合
  8. easyui tree 判断是否是叶子节点
  9. LeetCode OJ 223.Rectangle Area
  10. UVA732【DFS+栈】
  11. 使用Spring+Junit4.4进行测试
  12. js逗号表达式
  13. Net Core API网关Ocelot
  14. 利用salt搭建hadoop集群
  15. 使用 Azure 资源管理器向 Windows VM 应用策略
  16. 【亲测有效】Win10家庭版Microsoft Edge页面出现乱码的两种解决方案及gpedit.msc命令无法使用的解决策略
  17. 缩减apk大小
  18. C# Timer自带定时器
  19. java技术秘籍 转摘
  20. ftm时钟源

热门文章

  1. percona
  2. 获取表单的初始值,模拟placeholder属性
  3. 判断webkit中的js引擎是否是v8
  4. [Stanford 2011] Views 知识点
  5. Payoneer欧洲收款账户开通激活及使用-用于接收欧洲公司资金和欧元收款
  6. [LeetCode]题解(python):060-Permutation Sequence
  7. [LeetCode]题解(python):030-Substring with Concatenation of All Words
  8. iOS开发中 在MRC中让某些类使用ARC编译 或者相反
  9. [代码片段]读取BMP文件
  10. AJAX中UPDATEPANEL配合TIMER控件实现局部无刷新