Is there a difference between foreach and map?

Viewed 79243

Ok this is more of a computer science question, than a question based on a particular language, but is there a difference between a map operation and a foreach operation? Or are they simply different names for the same thing?

9 Answers

Different.

foreach iterates over a list and performs some operation with side effects to each list member (such as saving each one to the database for example)

map iterates over a list, transforms each member of that list, and returns another list of the same size with the transformed members (such as converting a list of strings to uppercase)

The important difference between them is that map accumulates all of the results into a collection, whereas foreach returns nothing. map is usually used when you want to transform a collection of elements with a function, whereas foreach simply executes an action for each element.

the most 'visible' difference is that map accumulates the result in a new collection, while foreach is done only for the execution itself.

but there are a couple of extra assumptions: since the 'purpose' of map is the new list of values, it doesn't really matters the order of execution. in fact, some execution environments generate parallel code, or even introduce some memoizing to avoid calling for repeated values, or lazyness, to avoid calling some at all.

foreach, on the other hand, is called specifically for the side effects; therefore the order is important, and usually can't be parallelised.

If you're talking about Javascript in particular, the difference is that map is a loop function while forEach is an iterator.

Use map when you want to apply an operation to each member of the list and get the results back as a new list, without affecting the original list.

Use forEach when you want to do something on the basis of each element of the list. You might be adding things to the page, for example. Essentially, it's great for when you want "side effects".

Other differences: forEach returns nothing (since it is really a control flow function), and the passed-in function gets references to the index and the whole list, whereas map returns the new list and only passes in the current element.

ForEach tries to apply a function such as writing to db etc on each element of the RDD without returning anything back.

But the map() applies some function over the elements of rdd and returns the rdd. So when you run the below method it won't fail at line3 but while collecting the rdd after applying foreach it will fail and throw an error which says

File "<stdin>", line 5, in <module>

AttributeError: 'NoneType' object has no attribute 'collect'

nums = sc.parallelize([1,2,3,4,5,6,7,8,9,10])
num2 = nums.map(lambda x: x+2)
print ("num2",num2.collect())
num3 = nums.foreach(lambda x : x*x)
print ("num3",num3.collect())
Related