Groovy 匕首方法

匕首,短小精悍,用简洁的代码实现强大的功能,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]
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值