Groovy使用List集合

本文介绍了Groovy语言中列表的基本操作方法,包括元素获取、范围选取、迭代、元素查找、排序、去重、连接字符串、元素替换等实用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 获取List集合中的元素

def lst = [1,3,4,1,8,9,2,6]
println lst[-1]
println lst[-2]

输出结果:

6
2


2 使用Range(范围)对象获得集合中连续的几个值

def lst = [1,3,4,1,8,9,2,6] //从左至右取值
println lst[2..5]
println lst[-1..-4]
输出结果:
[4, 1, 8, 9]//从右至左取值

输出结果:
[6, 2, 9, 8]


3  迭代ArrayList


//从左至右顺序迭代
lst = [1,3,4,1,8,9,2,6]
lst.each{ print "${it}," }
输出结果:
1,3,4,1,8,9,2,6,
 
//从右至左反方向迭代
lst = [1,3,4,1,8,9,2,6]
lst.each{ print "${it}," }

输出结果:
6,2,9,8,1,4,3,1,
 
//迭代中显示索引
def lst = [1,3,4,1,8,9,2,6]
lst.eachWithIndex{ it,i -> print("${i},") }

输出结果:
0,1,2,3,4,5,6,7,


4 使用List的collect方法


//查找list元素
/*find()会找到第一次出现的匹配对象,它只会迭代到闭包返回true为止。已得到true,find方法就会停止迭代,并将当前的元素返回。如果遍历结束也没得到true,则返回null。*/
lst = [1,3,4,1,8,9,2,6]
println lst.find{ it > 4 }
输出结果:
8

//查找list元素,返回所有符合条件元素
lst = [1,3,4,1,8,9,2,6]
println lst.findAll{ it > 4 }

输出结果:
[8,9,6]
 
//查找list元素,返回元素下标
lst = [1,3,4,1,8,9,2,6]
println lst.findAllIndexOf{ it == 4 }

输出结果:
2


5 使用List的排序

def ids = [5,6,3,7,1,4,9] 
//可以认为是 Comparator 排序 
ids.sort { a,b-> 
    return -a.compareTo(b) 
} 
println ids 
//自然排序 
ids.sort(); 
println ids

输出结果:
[9, 7, 6, 5, 4, 3, 1]
[1, 3, 4, 5, 6, 7, 9]


6 list去重


lst = [1,3,1,1,8,9,2,6]
println lst.unique()

输出结果:
[1, 3, 8, 9, 2, 6]


7 将list元素链接成一个字符串



lst = ['顺丰海淘','就是好','只卖正品']
println lst.join('')
println lst.join(',')

输出结果:
顺丰海淘就是好只卖正品
顺丰海淘,就是好,只卖正品


8 元素替换


lst = ['顺丰海淘','就是好','只卖正品']
lst[0] = ['sfht','.com']
println lst.flatten()

输出结果:
[sfht, .com, 就是好, 只卖正品]
 
9  +/-操作符

lst = ['顺丰海淘','就是好','只卖正品']
println lst - ['就是好']

输出结果:
[顺丰海淘, 只卖正品]
 
lst = ['顺丰海淘','就是好','只卖正品']
println lst + ['你说呢']

输出结果:
[顺丰海淘, 就是好, 只卖正品, 你说呢]


10 list元素拉平

lst = [[1,2],'顺丰海淘','就是好','只卖正品']
println lst.flatten()

输出结果:

[1,2,'顺丰海淘','就是好','只卖正品']


11  list的 集合操作

assert 'a' in ['a','b','c'] // returns true if an element belongs to the list

 assert ['a','b','c'].contains('a') // equivalent to the `contains` method in Java

 assert [1,3,4].containsAll([1,4]) // `containsAll` will check that all elements are found

 assert [1,2,3,3,3,3,4,5].count(3) == 4 // count the number of elements which have some value

 assert [1,2,3,3,3,3,4,5].count {
 it%2==0 // count the number of elements which match the predicate
 } == 2

 assert [1,2,4,6,8,10,12].intersect([1,3,6,9,12]) == [1,6,12]

 assert [1,2,3].disjoint( [4,6,9] )

 assert ![1,2,3].disjoint( [2,4,6] )



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值