One useful Groovy iterator is the SyncIterator, based on Ruby's SyncEnumerator which can iterate across several data structures at the same time. It makes use of DefaultTypeTransformation.asCollection() to perform the same coercion that Groovy uses by default to implement methods such as each(), collect(), and the like...
Another useful iterator is the Generator, which takes a closure and offers up the stuff it yields as an iterator, without having to keep all of the generated data around in memory. (It's based loosely on Ruby 1.9's Generator, which was also the challenge in Ruby Quiz #66)
Note that Groovy doesn't have this concept built in. Its MethodClosure to Iterator conversion loads everything into an array all at once, which isn't a particularly good idea you may be running find() on it, and only need to generate the first item to find what you're looking for.
For example, consider the following use of a Generator:
As the Groovy runtime implements this now, you would exhaust all available ram when converting the MethodClosure to an iterator, before find() was ever called. With a Generator, values are only generated on demand.
- because of the use of threads, the generator may generate one more value than is actually needed before the garbage collector disposes of the generator.
- Exceptions thrown from the generator method are not propagated back to the caller (again, because the function is called on a different thread)