What is the difference between Groovy each and forEach?

orbfish picture orbfish · Feb 28, 2016 · Viewed 14.7k times · Source

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

Answer

Emmanuel Rosa picture Emmanuel Rosa · Feb 28, 2016

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.