each() in Groovy

来源:互联网 发布:网页源代码 隐藏数据 编辑:程序博客网 时间:2024/06/04 18:09

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.Entryper call. This isn’t very convenient — you have to, you know, make Javacalls and stuff. If your closure specifies two arguments, though, thefirst argument will receive the key, and the second the value, for eachentry 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
}
原创粉丝点击