Groovy中定义列表的方式有两种,一是使用Java中的方法来创建列表,二是使用Groovy语言中的方法来创建列表
- def list = new ArrayList() // java中的定义方式
- // Groovy中定义列表的方式
- def list = [1, 2, 3, 2, 4, 2, 4] // ArrayList
Groovy中数组的定义方式也有两种,一是使用Java中的方法来创建数组,二是使用Groovy语言中的方法来创建数组,使用as关键字
- // 定义数组使用as关键字
- def array = [1, 2, 1, 34] as int[]
- int[] array1 = [1, 2, 3, 4] // 使用强类型定义数组
注:因为Groovy中数组的操作方法与列表的操作方法相同,所以我只介绍列表的操作方式
- def testList = [1]
- testList.add(6)
- def testList = [1]
- testList.leftShift(7)
- def testList = [1]
- testList << 8
注:这种方式产生的是一个新的列表
- def testList = [1]
- def PutList = testList + 9
- def LIST = [6, -3, 9, 2, -7, 1, 5,5]
- LIST.remove(7)
LIST.remove((Object) 6)
LIST.removeAt(1)
LIST.removeElement(6)
LIST.removeAll{return it % 2 == 0}
- def sortList = [5, 67, -1, 46, 4, -33]
- Collections.sort(sortList)
- println sortList
此sort方法还有一个重载方法,可以按照我们自定义的规则进行排序
- Comparator mc = { a, b -> a == b ? 0 : Math.abs(a) < Math.abs(b) ? -1 : 1 } // 使用闭包进行判断条件的封装
- Collections.sort(sortList, mc)
- println sortList
Groovy 中为我们提供的sort方法,直接就可以进行排序
- sortList.sort()
- println sortList
Groovy中的sort方法还可以搭配闭包进行使用
- sortList.sort { a, b -> a == b ? 0 : Math.abs(a) > Math.abs(b) ? -1 : 1 }
- println sortList
字符串的排序,根据字符串的长度进行排序,不指定排序规则,就按照首字母的ASCLL码进行排序
- def sortStringList = ["abc", "zfj", "z", "Lucy"]
- sortStringList.sort { it -> return it.length() }
- println sortStringList
find方法找出的是第一个符合条件的元素
- def findList = [-3, 9, 6, 2, -7, 5]
- int result = findList.find{return it % 2 == 0}
findAll方法找出所有符合条件的元素,并把它封装为java.util.ArrayList进行返回
ArrayList result = findList.findAll{return it % 2 == 0}
any方法搭配闭包使用,在列表中查找条件的元素,只要找到一个符合条件的元素就返回true,反之则返回false
def result = findList.any { return it % 2 == 0 } // result的值为布尔类型
此方法与any相反,必须列表中的元素满足闭包中的条件才返回true,反之则返回false
def result = findList.every { return it % 2 == 0 }
这里只是介绍Groovy中的用法,还可以使用java中的indexof等方法,进行列表查找,这里就不介绍了
min方法查找最小值,max方法查找最大值
- def min= findList.min()
- def max= findList.max()
这里的两个方法,也可以搭配闭包进行自定义大小比较
def result = findList.min{return Math.abs(it)}
def result = findList.count { return it % 2 == 0 }