集合的声明及循环遍历
println "java 声明集合"
List javaList = new ArrayList()
javaList.add(1)
javaList.add(3)
javaList.add(5)
println "groovy 声明集合"
def groovyList = [1, 3, 5]
println "groovyList type is : ${groovyList.class}"
def intArray = [1, 3, 5] as int[]
println "intArray type is : ${intArray.class}"
groovyList << 7
groovyList[4] = 9
println "groovyList[-1] value is ${groovyList[-1]}"
println "groovyList[10] value is ${groovyList[10]}"
println "groovy 遍历集合 方式1 for-in"
for (i in groovyList) {
print i + " "
}
println "\ngroovy 遍历集合 方式2 each"
def eachList = groovyList.each {
print it + " "
}
eachList[0] = 7
println "\ngroovyList content is : "+ groovyList
println "eachList content is : "+ eachList
println "groovy 遍历集合 方式3 collect"
def collectList = groovyList.collect {
print it + " "
it*2
}
collectList[0] = 2
println "\ngroovyList content is : "+ groovyList
println "collectList content is : "+ collectList
输出结果为
java 声明集合
groovy 声明集合
groovyList type is : class java.util.ArrayList
intArray type is : class [I
groovyList[-1] value is 9
groovyList[10] value is null
groovy 遍历集合 方式1 for-in
1 3 5 7 9
groovy 遍历集合 方式2 each
1 3 5 7 9
groovyList content is : [7, 3, 5, 7, 9]
eachList content is : [7, 3, 5, 7, 9]
groovy 遍历集合 方式3 collect
7 3 5 7 9
groovyList content is : [7, 3, 5, 7, 9]
collectList content is : [2, 6, 10, 14, 18]
集合中常用方法
def list = ["a","b","c","a"]
def findValue = list.find {
it == "b"
}
println "findValue is : ${findValue}"
def findAllValue = list.findAll {
it == "a"
}
println "findAllValue is : ${findAllValue}"
def expansionList = list*.toUpperCase()
println "expansionList is : ${expansionList}"
println "list is : ${list}"
def anyCheckResult = list.any {
it == 'a'
}
println "anyCheckResult is : ${anyCheckResult}"
def everyCheckResult = list.every {
it == 'a'
}
println "everyCheckResult is : ${everyCheckResult}"
输出结果为
findValue is : b
findAllValue is : [a, a]
expansionList is : [A, B, C, A]
list is : [a, b, c, a]
anyCheckResult is : true
everyCheckResult is : false
集合声明及常用方法
def groovyMap = [B: "Benz", "L": "Lexus", A: "Audi"]
println "groovyMap type is : " + groovyMap.getClass()
println "groovyMap.B value is : ${groovyMap.B}"
println "groovyMap.'B' value is : ${groovyMap.'B'}"
println "groovyMap['B'] value is : ${groovyMap['B']}"
groovyMap.F = 'Ferrari'
groovyMap << [P:"Porsche"]
groovyMap.each {
print "${it} "
}
println "\nkey-value接收遍历"
groovyMap.each {
key , value ->
print "key = ${key} , value = ${value}"
}
println "\n展开操作符获取key集合"
def getKey = groovyMap*.getKey()
println "getKey is : ${getKey}"
输出结果
groovyMap type is : class java.util.LinkedHashMap
groovyMap.B value is : Benz
groovyMap.'B' value is : Benz
groovyMap['B'] value is : Benz
B=Benz L=Lexus A=Audi F=Ferrari P=Porsche
key-value接收遍历
key = B , value = Benzkey = L , value = Lexuskey = A , value = Audikey = F , value = Ferrarikey = P , value = Porsche
展开操作符获取key集合
getKey is : [B, L, A, F, P]