Simple question that I haven't been able to find a simple answer for on the googles: what is the difference between Groovy's each and forEach loops?
I made a simple example and the syntax and behavior seem identical:
[1, 2].each { println it } [1, 2].forEach { println it }
Both print:
1 2
The only example I see of both in the Groovy Language Documentation seems to touch on the difference between lambdas and closures, but I can't relate that to the examples I've tried.
Thank you
each differs for the arguments passed to the callback. If you use _. forEach , the first argument passed to the callback is the value, not the key. So if you don't bother at all about the key you should use _.
groovy Ways of Iteration in Groovy Each and EachWithIndex each and eachWithIndex are methods to iterate over collections. each have it (default iterator) and eachWithIndex have it , index (default iterator, default index). We can also change the default iterator/index.
The first distinction between each()
and forEach()
is that each()
is provided by Groovy's GDK, while forEach()
is provided by Java 8 (so it is not available in prior versions of Java.
Another difference is that each()
accepts a Groovy closure while forEach()
accepts a Consumer. From Groovy, this difference is not noticeable because Groovy transparently coerces the closure to a Consumer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With