Deadshot Deadshot - 5 months ago 8
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

Iterable.forEach()
, 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) {
doSomething(s);
}


However, with the introduction of
Iterable.forEach()
in Java 8, such a program could look like this:

stringList.forEach(this::doSomething);


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

Answer

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.

Comments