coming from java I’m used to using break & continue to manipulate loops. Groovy doesn’t allow these keywords, so iterating with closures presented a problem.

Consider a piece of code like:

List people = // instantiate some Person ’s (idiots at the back)

// print the useful people
for (Person person : people) {
    if (person.isNuisance()) {
        break;
    }
    System.out.println(”name : ” + person.getName());
}

To achieve the same effect in groovy, the common trick is to use .find {} rather than .each{}

find loops over all the items in the list just like each, except it breaks out and returns the current object when a true condition is returned from the closure. So there is no reason why you can’t add logic to find, and use it in this manner

class Person { String name; boolean nuisance}

def people = [new Person(name:"person1",nuisance:false),
              new Person(name:"person2",nuisance:false),
	      new Person(name:"person3",nuisance:true),
	      new Person(name:"person4",nuisance:true)]

people.find() {
	if (it.nuisance) return true // break out
	println it.name
}