java – Java 8 Iterable.forEach () vs foreach loop

I feel I need to extend my comment a little …

About paradigm \ style

This is probably the most notable aspect. FP has become popular due to what you can avoid by avoiding side effects. I will not delve into the benefits to be gained from this, as this is unrelated to the question.

However, I will say that the iteration using Iterable.forEach is FP inspired and rather the result of bringing more FP into Java (ironically, I would say there isn’t much use for forEach in pure FP, as it does nothing except introducing effects collateral).

In the end I would say that it is rather a matter of taste \ style \ paradigm that you are currently writing in.

Information on parallelism.

From a performance standpoint, there are no notable benefits promised by using Iterable.forEach over foreach (…).

According to official documents on Iterable.forEach :

Performs the specified action on the contents of Iterable, in the order elements occur when iterating, until all elements have been processed or the action throws an exception.

… the documents are clear enough that there will be no implicit parallelism. Adding one would be the violation of LSP.

Now, there are “parallel collections” that are promised in Java 8, but to work with the ones I need most and put a little more care to use them (see mschenk74 answer for example).

BTW: in this case Stream.forEach will be used, and does not guarantee that the actual work will be done in parallel (depends on the underlying collection).

UPDATE: it may not be that obvious and a little strained at a glance, but there is another aspect of the style and readability perspective.

First of all, old sparrows are plain and old. Everyone already knows them.

Second, and more importantly – you probably want to use Iterable.forEach only with one-liner lambdas. If the “body” gets heavier – they tend not to be – that legible. You have 2 options from here – use inner classes (yuck) or use the old forloop. Often people get annoyed when they see the same things (iteratins over collections) being executed in various ways / styles in the same code base, and this seems to be the case.

Again, this may or may not be a problem. It depends on the people working on the code.

Leave a comment