在Scala中,我可以使用以下方法展平集合:
val array = Array(List("1,2,3").iterator,List("1,4,5").iterator)
//> array : Array[Iterator[String]] = Array(non-empty iterator, non-empty itera
//| tor)
array.toList.flatten //> res0: List[String] = List(1,2,3, 1,4,5)
但是我怎样才能在Spark中执行类似的操作?
阅读API文档http://spark.apache.org/docs/0.7.3/api/core/index.html#spark.RDD似乎没有提供此功能的方法?
答案 0 :(得分:34)
使用flatMap
和identity
Predef
,这比使用x => x
更具可读性,例如
myRdd.flatMap(identity)
答案 1 :(得分:30)
尝试使用身份地图功能(y => y
)的flatMap:
scala> val x = sc.parallelize(List(List("a"), List("b"), List("c", "d")))
x: org.apache.spark.rdd.RDD[List[String]] = ParallelCollectionRDD[1] at parallelize at <console>:12
scala> x.collect()
res0: Array[List[String]] = Array(List(a), List(b), List(c, d))
scala> x.flatMap(y => y)
res3: org.apache.spark.rdd.RDD[String] = FlatMappedRDD[3] at flatMap at <console>:15
scala> x.flatMap(y => y).collect()
res4: Array[String] = Array(a, b, c, d)