一、列表
•列表的定義
//初始化
def list = [1, 2, 3, 4, 5]
//看起來像是java中的數組,那麼groovy中如何定義數組
def array = [1, 2, 3, 4, 5] as int[] //使用as關鍵字定義一個int數組
int[] array2 = [1, 2, 3, 4, 5] //使用強類型定義一個數組
def array3 = new int[5] //像Java中一樣定義
//以此類推,就能定義其他類型的list
def linkList = [1, 2, 3, 4, 5] as LinkedList
println linkList.class //class java.util.LinkedList
•列表的操作(增、刪、查、排)
1.list新增
/**
* list的添加元素
*/
def list = [1, 2, 3, 4, 5]
//以下方法都是在list後面插入一個元素
list.add(6)
println list // [1, 2, 3, 4, 5, 6]
list.leftShift(7)
println list //[1, 2, 3, 4, 5, 6, 7]
list << 8
println list.toListString() //[1, 2, 3, 4, 5, 6, 7, 8]
def plusList = list + 9
println plusList.toListString() //[1, 2, 3, 4, 5, 6, 7, 8, 9]
2.list刪除
/**
* list的刪除操作
*/
def list = [1, 2, 3, 4, 5, 6, 7, 8]
list.remove(7)
println list //[1, 2, 3, 4, 5, 6, 7]
list.remove((Object) 7)
println list //[1, 2, 3, 4, 5, 6]
list.removeAt(7) //java.lang.IndexOutOfBoundsException
list.removeElement(6) // [1, 2, 3, 4, 5]
list.removeAll { return it % 2 == 0 } //[1, 3, 5]
println list - [1, 5] //[3]
3.list排序
/**
* list的排序
*/
def sortList = [-1, 6, 9, 8, -3, 0, 2]
//java中的排序
//Collections.sort(sortList) //默認由小到大排序
//println sortList //[-3, -1, 0, 2, 6, 8, 9]
//由大到小排序
//Collections.sort(sortList, new Comparator<Integer>() {
// @Override
// int compare(Integer o1, Integer o2) {
// return o2 - o1
// }
//})
//println sortList //[9, 8, 6, 2, 0, -1, -3]
//上面的Comparator可以用groovy中的閉包定義(像java8中的lambda表達式)
//def mComparator = { a, b -> a == b ? 0 : Math.abs(a) < Math.abs(b) ? -1 : 1 } //根據絕對值由小到大排序
//Collections.sort(sortList, mComparator)
//println sortList //[0, -1, 2, -3, 6, 8, 9]
//groovy中的DefaultGroovyMethods類提供了這樣的排序方法
//sortList.sort()
//println sortList //[-3, -1, 0, 2, 6, 8, 9]
//傳入閉包根據自定義的規則排序
//sortList.sort { a, b -> a == b ? 0 : Math.abs(a) < Math.abs(b) ? 1 : -1 } //根據絕對值由大到小排序
//println sortList //[9, 8, 6, -3, 2, -1, 0]
//也可對對象進行排序(根據對象的某些屬性去比較)
def sortStringList = ['android', 'groovy', 'java', 'python', 'Hello']
//sortStringList.sort { it -> return it.size() } //根據字符串的長度排序
//println sortStringList //[java, Hello, groovy, python, android]
//查看sort方法的源碼,當傳入的閉包只有一個參數時,會調用Collections.sort(list, new OrderBy(closure));
//其他時候調用Collections.sort(list, new ClosureComparator(closure));
//那麼我們傳入的是一個參數的閉包,最終實際比較的就是我們傳入的size,然後根據size的比較結果對sortStringList進行排序
/**
* int params = closure.getMaximumNumberOfParameters();
* if (params == 1) {* Collections.sort(list, new OrderBy(closure));
*} else {* Collections.sort(list, new ClosureComparator(closure));
*}* **/
//比如我們可以根據首字母排序(忽略大小寫)
sortStringList.sort { it[0].toLowerCase() }
println sortStringList //[android, groovy, Hello, java, python]
4.列表的查找,跟閉包與String的結合使用中講解的類似
/**
* list的查找
* */
def findList = [-1, 6, 9, 8, -3, 0, 2]
def result = findList.find { it % 2 == 0 }//查找滿足第一個符合條件的元素
println result //6,第一個偶數
def listResult = findList.findAll { it % 2 == 0 } //查找所有符合條件的元素
println listResult //[6, 8, 0, 2]
def anyResult = findList.any { it -> return it % 2 != 0 } //是否有一個滿足條件(有一個是奇數)
println anyResult //true
def everyResult = findList.every { it -> return it % 2 != 0 } //是否所有都滿足條件
println everyResult //false
println findList.max() // 9 最大值
println findList.min() // -3 最小值
class Student {
def grade
}
def stu1 = new Student(grade: 85)
def stu2 = new Student(grade: 60)
def stu3 = new Student(grade: 75)
def stu4 = new Student(grade: 100)
def stu5 = new Student(grade: 10)
def stuList = [stu1, stu2, stu3, stu4, stu5]
println stuList.max { it.grade }.grade //100 查找分數最高的學生的分數
println stuList.min { it.grade }.grade //10 查找分數最低的學生的分數
def count = stuList.count { it.grade >= 85 } //統計符合條件的數量
println count //2
//還有其它查找的方法,比如說last(),lastIndexOf()等與java中一致的,就不再重複說明了
二、映射(Map)
Map的定義
def map = new HashMap() //java方式
def colors = [red: 'ff0000', green: '00ff00', blue: '0000ff'] //groovy中,直接以key:value的形式定義,以逗號分隔元素
//獲取map中的值
println colors['red'] //ff0000
println colors.getAt('green') //00ff00
println colors.blue //0000ff
Map的操作(增、刪、遍歷、查、排)
1.Map增添元素
//添加一個元素
//同樣有java中的put()方法
colors.yellow = 'ffff00'
println colors.toMapString() //[red:ff0000, green:00ff00, blue:0000ff, yellow:ffff00]
//添加一個集合
def anotherColor = [black: '000000', white: 'ffffff']
colors.complex = anotherColor
println colors.toMapString() //[red:ff0000, green:00ff00, blue:0000ff, yellow:ffff00, complex:[black:000000, white:ffffff]]
//可添加其它類型
def another = [a: 1, b: 2, c: 3]
colors.another = another
println colors.toMapString() //[red:ff0000, green:00ff00, blue:0000ff, yellow:ffff00, complex:[black:000000, white:ffffff], another:[a:1, b:2, c:3]]
println colors.getClass() //class java.util.LinkedHashMap,查看類型需要使用getClass(.class會讓編譯期以爲是要添加一個ket爲class的值)
2.Map刪除
//與java中的map刪除基本一致
colors.remove('complex')
colors.remove('another')
println colors.toMapString() //[red:ff0000, green:00ff00, blue:0000ff, yellow:ffff00]
colors.removeAll {it.value.contains("0000")} //閉包刪除
println colors // [green:00ff00, yellow:ffff00]
3.map遍歷
def students = [
1: [number: '0001', name: 'java',
score : 55, sex: 'male'],
2: [number: '0002', name: 'android',
score : 62, sex: 'female'],
3: [number: '0003', name: 'kotlin',
score : 73, sex: 'female'],
4: [number: '0004', name: 'groovy',
score : 66, sex: 'male']]
//遍歷
students.each { def student -> println "the key is ${student.key},the value is ${student.value}" }
//帶索引遍歷 entry方式
students.eachWithIndex {
def student, int index -> println "the index is ${index},the key is ${student.key},the value is ${student.value}"
}
//帶索引遍歷 key-value方式
students.eachWithIndex {
key, value, index -> println "the index is ${index},the key is ${key},the value is ${value}"
}
/**
* 帶索引輸出結果
*/
//the index is 0,the key is 1,the value is [number:0001, name:java, score:55, sex:male]
//the index is 1,the key is 2,the value is [number:0002, name:android, score:62, sex:female]
//the index is 2,the key is 3,the value is [number:0003, name:kotlin, score:73, sex:female]
//the index is 3,the key is 4,the value is [number:0004, name:groovy, score:66, sex:male]
4.Map查找
/**
* 查找
*/
def students = [
1: [number: '0001', name: 'java',
score : 55, sex: 'male'],
2: [number: '0002', name: 'android',
score : 62, sex: 'female'],
3: [number: '0003', name: 'kotlin',
score : 73, sex: 'female'],
4: [number: '0004', name: 'groovy',
score : 66, sex: 'male']]
def entry = students.find { def student -> student.value.score >= 60 } //找到第一個及格的學生
println entry // 2={number=0002, name=android, score=62, sex=female}
def entryMap = students.findAll { def student -> student.value.score >= 60 } //找到所有及格的學生
println entryMap //[2:[number:0002, name:android, score:62, sex:female], 3:[number:0003, name:kotlin, score:73, sex:female], 4:[number:0004, name:groovy, score:66, sex:male]]
def count = students.count { def student -> student.value.score >= 60 && student.value.sex == 'female' } //統計所有及格的女學生的數量
println count //2
def nameList = students
.findAll { def student -> student.value.score >= 60 } //找到所有及格的學生
.collect { return [name: "${it.value.name}", score: "${it.value.score}"] } //過濾,只要名字和分數 ,collect返回的是一個list
println nameList // [[name:android, score:62], [name:kotlin, score:73], [name:groovy, score:66]]
//分組
def groupMap = students.groupBy { def student -> return student.value.score >= 60 ? '及格' : '不及格' }
println groupMap.toMapString() //[不及格:[1:[number:0001, name:java, score:55, sex:male]], 及格:[2:[number:0002, name:android, score:62, sex:female], 3:[number:0003, name:kotlin, score:73, sex:female], 4:[number:0004, name:groovy, score:66, sex:male]]]
5.Map排序
/**
* 排序
*/
def students = [
1: [number: '0001', name: 'java',
score : 55, sex: 'male'],
2: [number: '0002', name: 'android',
score : 62, sex: 'female'],
3: [number: '0003', name: 'kotlin',
score : 73, sex: 'female'],
4: [number: '0004', name: 'groovy',
score : 66, sex: 'male']]
def sortMap = students.sort { student1, student2 ->
Number score1 = student1.value.score
Number score2 = student2.value.score
score1 - score2
} //根據分數由小到大排序
//完整寫法
def sortMap2 = students.sort { def student1, def student2 ->
Number score1 = student1.value.score
Number score2 = student2.value.score
return score1 == score2 ? 0 : score1 < score2 ? 1 : -1
} //根據分數由大到小排序
println sortMap //[1:[number:0001, name:java, score:55, sex:male], 2:[number:0002, name:android, score:62, sex:female], 4:[number:0004, name:groovy, score:66, sex:male], 3:[number:0003, name:kotlin, score:73, sex:female]]
println sortMap2 //[3:[number:0003, name:kotlin, score:73, sex:female], 4:[number:0004, name:groovy, score:66, sex:male], 2:[number:0002, name:android, score:62, sex:female], 1:[number:0001, name:java, score:55, sex:male]]
三、範圍(Range)
範圍的概念:
Range繼承了List,是更輕量級的List,當在開發中需要使用類似數字範圍的簡單的List時,直接使用List相對來說比較重,可使用更加輕量級的Range
範圍的使用類型:
範圍可以使用滿足以下兩個條件的任意類型
1.該類型實現了next和previous方法,即重寫++和–操作符
2.該類型實現了java.lang.Comparable接口;也就是說實現了compareTo方法,即重寫<=>操作符
範圍的定義
def range = 1..10
println range[0] //1 獲取範圍的元素
println range.contains(10) //true 範圍是否包含某個元素
println range.from //1 範圍的起始值
println range.to // 10 範圍的終止值
//在groovy中Date類型也可以定義範圍
def today = new Date()
def yesterday = today - 1
def tomorrow = today + 1
def dateRange = yesterday..tomorrow
println dateRange.from //Thu Sep 06 14:24:47 CST 2018
println dateRange[1] //Fri Sep 07 14:24:47 CST 2018
println dateRange.to //Sat Sep 08 14:24:47 CST 2018
def age = [20, 22, 35, 45, 58]
def matchRange = 22..50
println age.grep(matchRange) //[22, 35, 45] 利用grep()獲取list中某個範圍的值
範圍的遍歷
/**
* 遍歷
*/
def range = 1..5
range.each { print "$it," } //1,2,3,4,5,
for (i in range) {
print "$i," //1,2,3,4,5,
}
switch/case中使用範圍
static String getGrade(Number number) {
def result
switch (number) {
case 0..<60:
result = '不及格'
break
case 60..<70:
result = '及格'
break
case 70..<85:
result = '良好'
break
case 85..100:
result = '優秀'
break
default:
result = "分數($number)應該在0..100"
break
}
return result
}
println getGrade(59)//不及格
println getGrade(60)//及格
println getGrade(70) //良好
println getGrade(85) //優秀
println getGrade(101) //分數(101)應該在0..100