Groovy的集合主要总结list以及map
直接使用[]来新建
def list1=[1,2,3,4]
def list2=[5,6] as LinkedList
println list1.class
println list2.class
结果:
class java.util.ArrayList
class java.util.LinkedList
使用下标获取,或者intRange获取子list
def list1=[1,2,3,4]
println list1[1]
println list1[2..3]
println list1[-1]
这里的子list获取会产生新的list,这里需要注意。
结果:
2
[3, 4]
4
遍历,for循环和each方法,collect方法
注意区别各个方法的区别
def list1=[1,2,3,4]
for(i in list1){
print " ${i}"
}
println()
//返回self
list1.each {
print " ${it}"
}
println()
//返回新的list
println list1.collect(){
it*3
}
//返回self
list1.eachWithIndex { int entry, int i ->
print "position ${i} value ${entry} "
}
println()
//返回self
list1.reverseEach {
print " ${it}"
}
结果:
1 2 3 4
1 2 3 4
[3, 6, 9, 12]
position 0 value 1 position 1 value 2 position 2 value 3 position 3 value 4
4 3 2 1
添加、删除、反转,拉平,查找等基本操作,
def list1=[1,2,3,4,1]
//返回self
println list1<<100
//返回新的list
println list1-1
//返回新的list
println list1.reverse()
//返回self
println list1<<[5,6]
//返回新的list
println list1.flatten()
//找到第一个符合的值
println list1.find{
it==1
}
//找到所有
println list1.findAll{
it==1
}
//找到某个就返回true
println list1.any{
it==2
}
//所有的都满足条件返回true
list1.flatten().every{
it>0
}
//*号展开操作符,返回新的list
println list1.flatten()*.multiply(5)
结果:
[1, 2, 3, 4, 1, 100]
[2, 3, 4, 100]
[100, 1, 4, 3, 2, 1]
[1, 2, 3, 4, 1, 100, [5, 6]]
[1, 2, 3, 4, 1, 100, 5, 6]
1
[1, 1]
true
[5, 10, 15, 20, 5, 500, 25, 30]
Map也有大量的扩展方法,只总结一些常用的,很多和list类似的,参考一下就能知道怎么用了。默认是LinkedHashMap
def emptyMap=[:] as HashMap
def map = [key1: "value1", key2: "value2", key3: "value3"]
println map.key1
println map.'key1'
println map['key1']
map.each {
key,value->
print "${key},${value}"
}
println()
println map.collect {
key,value->
"${key},${value}"
}
println()
//找到第一个
println map.find {
key,value->
value
}
map.reverseEach {
}
map.every {
}
//将闭包的返回值作为键,true一组,false一组
println map.groupBy {
it.key=='key1'
}
println map+[key4:'value4']
println map<<[key5:'value5']
println map-[key1:'value1']
println map*.getValue()
结果:
value1
value1
value1
key1,value1key2,value2key3,value3
[key1,value1, key2,value2, key3,value3]
key1=value1
[true:[key1:value1], false:[key2:value2, key3:value3]]
[key1:value1, key2:value2, key3:value3, key4:value4]
[key1:value1, key2:value2, key3:value3, key5:value5]
[key2:value2, key3:value3, key5:value5]
[value1, value2, value3, value5]