Groovy高效编程——‘匕首方法’的使用(更新于2007.09.14)(转
发布时间:2020-12-14 16:58:31 所属栏目:大数据 来源:网络整理
导读:? 关键字: grails 转载自 http://www.blogjava.net/BlueSUN/archive/2007/08/26/139460.html ? Groovy 提供了许多‘匕首方法’(匕首,短小精悍也~如 each,eachWithIndex,any,every,grep,join,sort,find,findAll,collect,groupBy,inject,revers
?
关键字: grails
转载自http://www.blogjava.net/BlueSUN/archive/2007/08/26/139460.html ? Groovy 提供了许多‘匕首方法’(匕首,短小精悍也~如 each,eachWithIndex,any,every,grep,join,sort,find,findAll,collect,groupBy,inject,reverse,tokenize,unique,max,min,count,sum等)来提升开发者的开发效率,但常被Java开发人员忽视。在这篇随笔中我将为您演示各方法的使用。
def?list?
=
?[
'
a
,?
b
c
] 运行结果:
list.each?{?elem? -> ??println?elem } a
b c 遍历map def?map?
?[name:
"
山风小子
Shanghai
] 运行结果:
map.each?{?key,?value? ??println? $key?:?$value } name?:?山风小子
address?:?Shanghai eachWithIndex 带index的each ]
list.eachWithIndex?{?elem,?i? $i?:?$elem 0?:?a 1?:?b 2?:?c any 只要存在一个满足条件(此例中的条件为elem.length() < 3)的element就返回true,否则返回false ab
abc
]
list.any?{?elem? ? ??elem.length()? < ? 3 true every 所有的element都满足条件才返回true,否则返回false ]
list.every?{?elem? false grep 符合条件的element会被提取出来,形成一个list 条件以closure的形式传入 ]
list.grep?{?elem? ??elem.length()? ["a",?"ab"] 条件以regex的形式传入,符合regex的element被提取出来形成一个list ] 运行结果:
list.grep( ~/ .. / ) ["ab"]
条件以collection的形式传入,在collection中的element被提取出来形成一个list,可以看作求两个collection的交集 ] 运行结果:
list.grep([ cde ]) join 用指定的字符连接collection中的element 2007
8
26
]
list.join( - 2007-8-26 sort 根据指定条件进行排序 ] 运行结果:
list.sort?{?e1,?e2? ?? return ?e1? ?e2 } [8,?26,?2007]
find 查找collection中满足条件的‘第一个’element ]
list.find?{?elem? ??elem? 30 8 findAll 查找collection中满足条件的‘所有’element ]
list.findAll?{?elem? collect 对collection的element进行处理,并将处理结果放到一个新的collection中 ]
list.collect?{?elem? * 2 ["aa",?"bb",?"cc"] 对map进行处理 ]
map.collect?{?entry? ${entry.key}?:?${entry.value} [name?:?山风小子,?address?:?Shanghai] groupBy 对collection中的element按给定条件进行分组 bc
] 运行结果:
list.groupBy?{?elem? ????elem.length() } [1:["a",?"b",?"c"],?2:["ab",?"bc"],?3:["abc"]]
inject 一个累积的过程,传入inject方法的'I'作为sum的初始值,在遍历collection的过程中,将处理结果( " $sum?$elem? ")保存到sum中 love
you
]
list.inject( I )?{?sum,?elem? ? ?? $sum?$elem? I?love??you? reverse 将collection中各element的次序颠倒一下 ] 运行结果:
list.reverse() ["c",?"a"]
颠倒字符串 list.reverse() cba
tokenize 指定分隔符,取得token集 a1/b2/c3/d4
.tokenize(
["a1",?"b2",?"c3",?"d4"]
unique 去除collection中重复的element ] 运行结果:
list.unique() max 求最大值 1
] 运行结果:
list.max() 3
按指定的比较内容(此例的比较内容为长度length),在collection中选出最大的element ]
list.max?{?elem? ??elem.length() } min与max类似,求最小值,再次就不演示用法了,用法与max相同,将上述代码中的max改为min即可 count 计数 ]
list.count( 2 对字符串"aaba"中的a进行计数 aaba
list.count( 3 sum 求和 ] 运行结果:
list.sum() 6
求字符串的‘和’,其实就是连接字符串 abc
最后,我想提醒各位一点:有时您可以将string看作list,对string使用适用于list的‘匕首方法’
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |