Groovy’s each method

It’s one of the coolest things I’ve ever seen. The each method on Object allows you to iterate over anything. Literally. Anything.

In Groovy, everything is an Object. And since the each method is defined on class Object, that means everything has an each method. Everything. That means you can iterate over anything.

Lists, Ranges, Strings, and Maps. Everything has an each, and you can use it to iterate. You don’t have to deal with for loops. And while Java 5’s for-each loop is kinda nice, it’s nowhere near as cool as Groovy’s each.

In Java, you have to use a for (or while) loop to iterate. You might do something like this:

for (String str : myList) {
    System.out.println(str);
}

Here’s some similar code in Groovy:

myList.each {
    println it
}

Isn’t Groovy just so much cooler? You don’t have to define the type and you don’t even need to give the variable a name - by default, the parameter is called it.

Leave a Reply