G$D/Groovy: Using each() on Collections

by Marc Hedlund

(For an overview of the G$D/Groovy series, see <http://www.oreillynet.com/pub/wlg/5789>.)

The each() method and collections

The each() method, which is a default method on every Groovy object, is a little bit magic. If you call each() on an integer, you get the integer back:

aNumber = 27;

aNumber.each() { println "${it}" }; // prints: "27"

If you call each on a string, you get one letter of the string (in order):

myName = "Marc";

myName.each() { println "${it}" };

// prints:

// M

// a

// r

// c

With collections, each() switches its behavior based on the type of collection. Lists hand each() one item of the list (in order), as you'd expect:

languageList = [ "java", "perl", "python", "ruby", "c#", "cobol",

"groovy", "jython", "smalltalk", "prolog", "m", "yacc" ];

languageList.each() { print " ${it}" };

// prints:

// java perl python ruby c# cobol groovy jython smalltalk prolog m yacc

Maps behave differently depending on how many arguments the closure expects. If you pass each() a closure that expects one argument (or you specify no arguments and use the default it parameter), the closure receives one Map.Entry per call. This isn't very convenient -- you have to, you know, make Java calls and stuff. If your closure specifies two arguments, though, the first argument will receive the key, and the second the value, for each entry in the Map. For instance:

weekMap = [ "Su" : "Sunday", "Mo" : "Monday", "Tu" : "Tuesday",

"We" : "Wedensday", "Th" : "Thursday", "Fr" : "Friday",

"Sa" : "Saturday" ];

weekMap.each() { key, value | println "${key} == ${value}" };

// prints:

// Su == Sunday

// We == Wedensday

// Mo == Monday

// Sa == Saturday

// Th == Thursday

// Tu == Tuesday

// Fr == Friday

The different behaviors of each() aren't documented very clearly on the Groovy site, so it helps to keep in mind where the method varies.


2004-09-16 11:08:20
C Omega
C Omega has pretty much the same thing - I'm curious - did both Groovy and Cw get it from the same source?
2004-09-16 11:55:17
C Omega
Hm, not sure, does anyone else know?
2004-12-12 11:45:12
A small typo
"stringMap" should be "weekMap"

at least it shows we're actually reading the articles :)

2004-12-12 11:53:57
A small typo
Thanks, Phil, fixed.