RDD: foreach() Action

Published on Author adminLeave a comment

foreach() is an action. Unlike other actions, foreach do not return any value. It simply operates on all the elements in the RDD. foreach() can be used in situations, where we do not want to return any result, but want to initiate a computation. A good example is ; inserting elements in RDD into database. Let us look at an example for foreach()

val testData=Array(1,2,3)
testData: Array[Int] = Array(1, 2, 3)

$ val inputrdd = sc.parallelize(testData)
inputrdd: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[2] at parallelize at :23

$ inputrdd.foreach{ x => {
 | println(x)
 | }





Leave a Reply

Your email address will not be published. Required fields are marked *