RDD: foreach() Action

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)
 | }
}

Oputput

1

2

3