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
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值