Deadshot Deadshot - 3 months ago 5x
Java Question

Is the replacement of a foreach loop with Iterable.forEach purely cosmetic?

My question concerns the Java foreach loop, introduced in Java 5, and

, introduced in Java 8.

Let's say that a program exists with a List of String values, and the function of that program is to iterate over each individual string and use it as a method parameter.

Such a program could look like this as of Java 5:

for (String s : stringList) {

However, with the introduction of
in Java 8, such a program could look like this:


My question is, is there any reason to use
instead of the foreach loop beyond the saving of a couple lines?


Providing a forEach makes the action to be performed on the elements pluggable and very flexible. It can be an immediate lambda, a MethodHandle or even a MethodHanlde dynamically composed from a static portion of behavior and a runtime-defined part of it. Internally, the creation of an explicit Iterator object may be avoided. Otherwise, you can, of course, simulate the same behavior by an external loop. This might not look so nice though.