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
}
- each() in Groovy
- 实战 Groovy: for each 剖析
- 实战 Groovy: for each 剖析
- 实战 Groovy: for each 剖析
- Groovy Tip 2 each方法和break
- 2.9.2Groovy的for-each用法
- Groovy in Action
- Groovy in SOAP UI
- Groovy in SOAP UI
- groovy in action
- Practice in groovy
- UT in groovy
- Page in each database
- Groovy in Action新鲜出炉!
- Groovy in action读书笔记1
- Groovy Tip 36 “in”关键字
- groovy list transpose和each的特殊用法
- AS3 中的 for each in
- Java技术:使您轻松地进行多线程应用程序编程
- 关于 TStringList 的用法
- CSDN 的朋友们大家进来看看
- PKU1611--The Suspects
- 用户 sa 登录失败 sql server
- each() in Groovy
- Oracle分页和排序常用的4条查询语句
- IE6下min-height 实现
- linux 各种信号及其含义
- 新手店铺的生存之道,【必看】——实际经验之谈
- TStringList用法(转载)
- linux内核代码架构图-清晰版
- PL/SQL常用函数
- loadruner测试sap portal