Home > Groovy > Groovy’s each method

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.

Advertisements
Tags:
  1. December 4, 2008 at 8:51 pm

    I found this post by Ted Naleid today about iteration in Groovy, and it shows a lot more examples of how to iterate.

  1. December 31, 2009 at 3:17 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: