Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Groovy each and forEach?

Tags:

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

like image 420
orbfish Avatar asked Feb 28 '16 00:02

orbfish


People also ask

What is the difference between forEach and each?

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 _.

What is each in groovy?

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.


1 Answers

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.

like image 93
Emmanuel Rosa Avatar answered Sep 20 '22 09:09

Emmanuel Rosa