1:集合克隆
def list1 = ['a', 'b', 'c']
def list2 = list1.clone()
2:list遍历
a:使用each进行遍历
def list = [1, 2, 3]
list.each {
println "Item: $it"
}
it是是与当前元素对应的隐式参数
遍历时候使用了${}操作符。只是省略了{}
b:使用eachWithIndex进行遍历 可以打印出集合的下标和下标对应的值
def list = ['a', 'b', 'c']
list.eachWithIndex { it, i -> // `it` is the current element, while `i` is the index
println "$i: $it"
}
' it '是当前元素,而' i '是索引
c:通过将其每个元素转换为其他元素来创建一个新列表通常也很有用。由于collect方法,这个操作(通常称为映射)是在Groovy中完成的
def list = [1, 2, 3]
def newList = list.collect { it * 2 }
println(newList)
上面是将list集合通过调用collect()把list中的值*2构成一个新的集合,构成的新集合是[2,4,6]
d:使用multiply()方法 快捷语法创建一个新集合
def list = [1, 2, 3]
def newList = list*.multiply(2)
println(newList)
e:使用collect. 参数list创建一个新的集合
def list = [0]
def originList = [1,2,3]
def newList = originList.collect(list) { it * 2 }
println(newList)
查找集合中某个值
a:使用find()方法. 找到第一个元素匹配标准
def list = [1, 2, 3]
println(list.find { it > 1 })
这个结果是2
b:使用findAll() 找到所有匹配的元素
def list = [1, 2, 3]
println(list.findAll{ it > 1 })
这个是[2,3]
c:使用findIndexOf() 查找第一个元素匹配标准的索引
def strList = ['a', 'b', 'c', 'd', 'e']
def index = strList.findIndexOf {
it in ['c', 'e', 'g']