之前老是分不清楚spark中flatmap和map的區別,如今弄明白了,總結分享給你們,先看看flatmap和map的定義。app
map()是將函數用於RDD中的每一個元素,將返回值構成新的RDD。函數
flatmap()是將函數應用於RDD中的每一個元素,將返回的迭代器的全部內容構成新的RDDspa
有些拗口,看看例子就明白了。scala
val rdd = sc.parallelize(List("coffee panda","happy panda","happiest panda party")) rdd.map(x=>x).collect res9: Array[String] = Array(coffee panda, happy panda, happiest panda party) rdd.flatMap(x=>x.split(" ")).collect res8: Array[String] = Array(coffee, panda, happy, panda, happiest, panda, party)
flatMap說明白就是先map而後再flat,再來看個例子code
val rdd1 = sc.parallelize(List(1,2,3,3)) scala> rdd1.map(x=>x+1).collect res10: Array[Int] = Array(2, 3, 4, 4) scala> rdd1.flatMap(x=>x.to(3)).collect res11: Array[Int] = Array(1, 2, 3, 2, 3, 3, 3)
這下應該徹底明白了吧,不懂給我留言,歡迎指正。it