aspose file tools*
The moose likes Groovy and the fly likes breaking from each closure Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Languages » Groovy
Bookmark "breaking from each closure" Watch "breaking from each closure" New topic
Author

breaking from each closure

Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8898

I am doing some calculation by iterating though a loop.

list.each{

}

When some condition to exit from loop . Having break statement is giving me a compile error.


Groovy
Peter Ledbrook
author
Greenhorn

Joined: Jul 15, 2009
Posts: 25
Hi,

The only way I know of to break out of a closure loop like this is to throw an exception - not an elegant solution I'm afraid. Even using the return statement won't help because it exits the closure, but not the each() method.

The usual solution is either to use a more appropriate iterator method, such as find(), or use a standard for loop:


Cheers,

Peter
Dave Klein
author
Ranch Hand

Joined: Aug 29, 2007
Posts: 77
Just to tack onto Peter's reply: I've yet to run into a situation where I couldn't come up with a better solution using more intelligent filtering instead of a break. So, yes, you can use a traditional Java loop with break but the exercise of trying to go without it may help you write better code.

Dave


Author of Grails: A Quick-Start Guide
Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8898

Well, actually I was using eachWithIndex. Now I would need to use the Java's enhanced for loop and also declare an integer as I need index or use the traditional for loop. Back to basics.
Marc Peabody
pie sneak
Sheriff

Joined: Feb 05, 2003
Posts: 4727

Hi Prad, if you find yourself wanting to use a break statement in an iteration method in Groovy, there's a really good chance you could benefit by using a different iteration method (like find or any).

If you post your code I can help you find the most appropriate method.


A good workman is known by his tools.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: breaking from each closure
 
Similar Threads
for Loop with y++ etc...
Ways to evaluate loops
need help using StringTokenizer
WA #2 ..... word association
WA #1.....word association