Groovy In Action 笔记 (5) -- List 相关
list在Groovy中很重要,记录一下list的一些见操作:
def list = [] list << 2 // list >> 2 // invalid assert list.size() == 1 assert list == [2] //传统添加 list.add(3) assert list.size() == 2 //groovy中统一的size 方法 assert list == [2,3] list << "a" assert list.size() == 3 assert list == [2,3,"a"] //groovy中不限制list中的数据类型,因为背后都是Object def other_list = [3] assert list - other_list == [2,"a"] // list可以直接相减 def other_list_a = [3,"b"] assert list - other_list_a == [2,"a"] // list可以直接相减 assert list * 2 == [2,3,"a",2,3,"a"] // list可以乘以一个数,达到复制效果 assert list.intersect(other_list) == [3] // 取交集 assert list.reverse() == ["a",3,2] assert !list.disjoint(other_list_a) // 判断有无交集 list.each {item -> println(item)} assert list.collect({it*2}) == [4,6,"aa"] // map def list_items = [1,2,3] assert list_items.inject {x,y -> x * y} == 6 // reduce or fold assert list_items.findAll {it % 2 == 0} == [2] //取值为偶数元素 assert list_items.join(",") == "1,2,3" // join 有时候很有用 def complex_list = [1,2,[3,4]] assert complex_list.flatten() == [1,2,3,4] //indexing def long_list = [1,2,3,4,5,6,7,8] assert long_list[1..3] == [2,3,4] assert long_list[-1] == 8 assert long_list[-1..-3] == [8,7,6] assert long_list[-1..0] == long_list.reverse() // 反转 assert long_list[-1..-8] == long_list.reverse() // 反转 assert long_list[1,2,4] == [2,3,5] assert long_list[0..<2] == [1,2]
下面尝试一个简单的快排算法:
/** * @author :ZackZhou * @date :Created in 2020/9/1 5:42 PM * @description :quick sort * @modified By: * @version: */ def quickSort(List input_list) { if(input_list.size() < 2) return input_list int middle = input_list.size().intdiv(2) def middle_element = input_list.get(middle) def middle_list = input_list.findAll{item -> item == middle_element} def left_list = input_list.findAll{item -> item < middle_element} def right_list = input_list.findAll{item -> item > middle_element} return (quickSort(left_list) + middle_list + quickSort(right_list)) } def raw_list = [3,24,5,6,6,7,82,6,7,2] quickSort(raw_list).each {println(it)}