//数组,集合,map
//数组
def a = new String[4];
a[0] = 'a';
a[1] = 'b';
a[2] = 'c';
a[3] = 'd';
println a.class;
List l = a.toList();
println l[0];
def strs = ['a','b','c'];
strs.each{
println it;
}
def array = ["a","b","c"];
println array.class; //class java.util.ArrayList
//向集合中添加数据可以用add(),<<
array.add("d");
array<<"common";
array = array +"e";
array[array.size()]=100;
println "数组大小 size="+array.size();
println("输出数组......");
for(i in 0..<array.size()){
println(array[i]);
}
//获取集合类对象中的元素位置时
array.eachWithIndex{
it,i->
println "values ${i} is ${it}"
}
println "倒数第一个元素:"+array[-1];
println "倒数第四个元素:"+array[-4];
array = array - "d";
for(i in 0..<array.size()){
println(array[i]);
}
def list = [1,2,3,4,5,6,7];
def newList = list.findAll{
it > 5
}
println 'find{}--'+newList;
array.addAll(list);
for(i in 0..<array.size()){
println(array[i]);
}
def have = list.any{it > 5};
println "list中是否有大于5的值 "+have;
println '-------list转成数组-----'
def listStr = list as String[];
for(it in listStr){
println it;
}
println "Map ----------------------------------";
//Map
def map = ["name":"dengm","age":23,"height":100];
//向map中添加元素
println map.size();
map.put("sex","boy");
println map.size();
map = map+["weight":60];
println map.size();
//变量map有两种方法
map.each{println it.key+"---"+it.value};
map.each{
k,v->
println "key="+k;
println "value="+v;
}
map.each({println it.getKey() + "--->" + it.getValue()});
//获取Map的元素
def sex = map.get("sex");
println("sex =" +sex);
println "sex = "+map["sex"];
println map.class; //null
println map.getClass(); //class java.util.LinkedHashMap
//排序
def sort = [3,45,2,34,8,98,76]
(0..<sort.size()-1).each{
i ->
(i+1..<sort.size()).each{
j ->
if(sort[i]>sort[j])
{
def num = sort[i]
sort[i] = sort[j]
sort[j] = num
}
}
}
println sort
学习groovy的小例子
最新推荐文章于 2021-10-13 14:58:30 发布