println "=========集合定义与索引元素=============";
def lst1 = [];
println lst1.class;//java.util.ArrayList
lst1.add("a");
lst1[2] = 8;
println lst1;//["a", null, 8]
println lst1.size();//3
def arr1 = lst1 as String[]//list转换为string数组
println arr1.class;//[Ljava.lang.String;
println arr1;//{"a", null, "8"}
def arr2 = {};//闭包
println arr2.class;//Test1$_main_closure1
def lst2 = new ArrayList();
println lst2.class;
lst2[0..2] = ['a','b','c',4];//索引下标的数量不需要与range的数量一致
println lst2.size;//4
println lst2;//["a", "b", "c", 4]
lst2[0..1] = [];//索引01移除
println lst2;//["c", 4]
//通过下标索引元素,正数从前往后,负数从后往前
println "=========增加和移除元素=============";
def lst3 = ["a","b","c"];
lst3 += "d";//lst3:["a", "b", "c", "d"] 等价: lst3 = lst3.plus("d");
lst3 +=["e","f","g"];//lst3:["a", "b", "c", "d", "e", "f", "g"] 等价:lst3 = lst3.plus(["e","f","g"]);
lst3 << "A" << "B";//["a", "b", "c", "d", "e", "f", "g", "A", "B"] 类似append操作
lst3 -= "d";//["a", "b", "c","e","f","g", "A", "B"] 等价:lst3 = lst3.minus([])
lst3 -= ["e","f","g","A","B"];//["a", "b", "c"]
lst3 *=2;//["a", "b", "c", "a", "b", "c"] 等价:lst3 = lst3.Multiply(2);
println lst3;
println "==========控制结构============";
def myList = ["a","b","c"];
println myList.isCase("b")//true
switch ('b') {
case myList://b是否在myList集合中
println 'containt b';
break;
default:
println 'not containt b';
break;
}
def mylst2 = myList.grep([2,"c"]);//从myList中过滤2,"c",并返回过滤到的数据
println mylst2;//["c"]
mylst2.clear();
if(!mylst2){
println 'list is empty';
}
def sb ='';
for(v in ['a','b','c']){
sb +=v;
}
println sb;//abc
println "==========集合方法使用============";
def lst5 = [1,2,3];
def lastObj = lst5.pop();//和js的数组方法一样,弹出最后一个元素
println lastObj;//3;
println lst5;//[1,2]
//lst5.push(5);
//println lst5;//[1,2,5]
lst5 = lst5.reverse();//反转元素
println lst5;//[2,1]
lst5 = lst5.sort();//自然排序
println lst5;//[1,2]
lst5 = [[1,2],[2,3,4],[5]];
lst5.sort({item -> item.size();});//根据元素长度
println lst5;
//lst5.remove(idx);//删除指定索引
//lst5.remove(obj);//删除指定对象
//lst5.remove(lst);//删除指定集合
lst5 = [1,2,3,4,1];
lst5 = lst5.find({item -> item*2==2});//返回一个object
println lst5;//1 ,没有找到返回null
lst5 = [1,2,3,4,1];
lst5 = lst5.findAll({item -> item*2 == 2});//返回一个数组
println lst5;//[1,1] ,没有找到返回[]
lst5 = [1,2,3,[4,5,[6,7]]];
lst5 = lst5.flatten();//将所有嵌套的集合合并成一个集合
println lst5;//[1, 2, 3, 4, 5,6,7]
lst5 = [1,2,3];
lst5 = lst5.disjoint([5,6,4]);//没有交集true,有交集false
println lst5;//true
lst5 = [1,2,3,4];
println lst5.max();//求集合中最大的值 4
println lst5.min();//求集合中最小的值 1
println lst5.every();
println lst5.every({item -> item >0})//集合中的元素必须都满足才返回true
println lst5.any();
println lst5.any({item -> item >3});//集合中的元素有一个满足就返回true
lst5.each({item -> println item});//使用each迭代集合
lst5.reverseEach({item -> println item});//使用reverseEach反向迭代集合
println lst5.sum();//所有元素求和
lst5 = lst5.join("-");//使用-拼接所有元素
println lst5;