匕首,短小精悍,用简洁的代码实现强大的功能,Groovy给我们提供了许多匕首方法,常用的如each,eachWithIndex,any,every,grep,join,sort,find,findAll,collect,groupBy,reverse,tokenize, unique,max,min,count,sum,multiply等匕首方法。
代码使用断言来测试程序的结果是否是正确的结果,以下代码经过 assert 测试无误。
each
遍历 list
def a = [1,2,3]
def cnt = 0
a.each {x->cnt += x}
assert cnt == 6 // 累加结果
遍历 map
def a = [1:'hello',2:'world']
def s = ''
a.each {key,value->s += value}
assert s == 'helloworld' // 累加结果
eachWithIndex
带下标的each
def a = [1,1,1]
def cnt = 0
a.eachWithIndex {x,i->cnt += i}
assert cnt == 3
every
所有的元素必须全部满足条件才返回 true,否则为null
def a = [1,2,3]
assert a.every{x->x>2} == false
assert a.every{x->x>0} == true
any
只要有一个元素满足条件就返回 true,否则返回 false
def a = [1,2,3]
assert a.any{x->x>2} == true
assert a.any{x->x>3} == false
grep
符合条件的元素会被提取出来组成一个 list
def a = [1,2,3]
assert a.grep{x->x>1} == [2,3]
assert a.grep{x->x>3} == []
join
用指定的字符串来连接Collectiion中的元素
def a= [1,2,3]
assert a.join("++") == "1++2++3"
tokenize
指定分隔符,分割出来的元素组成一个 list
def a = "1++2++3"
assert a.tokenize("++") == ['1','2','3']
sort
根据指定的条件进行排序
def a = [1,9,5,7,2]
a.sort({e1,e2-> return e1 - e2})
assert a == [1,2,5,7,9]
find
def a = [1,5,9,7,2]
assert a.find{x -> x > 6} == 9
findAll
def a = [1,5,9,7,2]
assert a.findAll{x -> x > 6} == [9,7]
collect
对 collection 中的元素进行处理,把处理好的结果放在一个新的 collection 中
def a = [1,2,3]
assert a.collect{x -> x * 2} == [2,4,6]
groupBy
对 collection 中的元素根据条件进行分组
def a = ['hello','world','thank','you']
a.groupBy {x->x.size()} == '[5:[hello, world, thank], 3:[you]]'
reverse
反转 collection 中的元素
def a= [1,2,3]
assert a.reverse() == [3,2,1]
unique
去除 collection 中重复的元素
def a = ['a','b','c','a','b','a']
assert a.unique() == ['a','b','c']
math函数
def a = [4,13,6,7,4]
assert a.max() == 13
assert a.min() == 4
assert a.count(4) == 2
assert a.sum() == 34
assert a.multiply(2) == [4, 13, 6, 7, 4, 4, 13, 6, 7, 4]