each() in Groovy

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.
 
def map = ["Java":"server", "Groovy":"server", "JavaScript":"web"]
map.each{
println it.key
println it.value
}

map.each{k,v->
println k
println v
}

좋은 웹페이지 즐겨찾기