美文网首页
Groovy基本语法

Groovy基本语法

作者: _Irving | 来源:发表于2023-04-26 16:55 被阅读0次
Groovy注释标记和Java一样,支持//或者/**/
Groovy语句可以不用分号结尾
Groovy中支持动态类型,即定义变量的时候可以不指定其类型。Groovy中,变量定义可以使用关键字def。注意,虽然def不是必须的,但是为了代码清晰,建议还是使用def关键字
   def variable1 = 1   //可以不使用分号结尾
   def varable2 = "I ama person"
   int y =1 //变量定义时,也可以直接指定类型
   def  int x = 1  
函数定义时,参数的类型也可以不指定。比如
String testFunction(arg1,arg2){//无需指定参数类型
  ...
}
除了变量定义可以不指定类型外,Groovy中函数的返回值也可以是无类型的。比如:
//无类型的函数定义,必须使用def关键字
def  nonReturnTypeFunc(){
    last_line   //最后一行代码的执行结果就是本函数的返回值
}
//如果指定了函数返回类型,则可不必加def关键字来定义函数
String getString(){
   return"I am a string"
}
函数返回值:Groovy的函数里,可以不使用returnxxx来设置xxx为函数返回值。
如果不使用return语句的话,则函数里最后一句代码的执行结果被设置成返回值。比如
//下面这个函数的返回值是字符串"getSomething return value"
def getSomething(){
     "getSomething return value" //如果这是最后一行代码,则返回类型为String
      1000//如果这是最后一行代码,则返回类型为Integer
}
Groovy对字符串支持相当强大,充分吸收了一些脚本语言的优点:
1  单引号''中的内容严格对应Java中的String,不对$符号进行转义
   def singleQuote='I am $ dolloar'  //输出就是I am $ dolloar
2  双引号""的内容则和脚本语言的处理有点像,如果字符中有$号的话,则它会$表达式先求值。
   def doubleQuoteWithoutDollar = "I am one dollar" //输出 I am one dollar
   def x = 1
   def doubleQuoteWithDollar = "I am $x dolloar" //输出I am 1 dolloar
3 三个引号'''xxx'''中的字符串支持随意换行 比如
   def multieLines = ''' begin
     line  1
     line  2
     end '''
最后,除了每行代码不用加分号外,Groovy中函数调用的时候还可以不加括号。比如:
println("test") ---> println"test"
list类
变量定义:List变量由[]定义,比如
def aList = [5,'string',true] //List由[]定义,其元素可以是任何对象
变量存取:可以直接通过索引存取,而且不用担心索引越界。如果索引超过当前链表长度,List会自动
往该索引添加元素
assert aList[1] == 'string'
assert aList[5] == null //第6个元素为空
aList[100] = 100 //设置第101个元素的值为10
assert aList[100] == 100
那么,aList到现在为止有多少个元素呢?
println aList.size  ===>结果是101


list操作:
def list = [1,2,3,4,5] 
list[1]        //Result: 2 
list[-2]       //Result: 4 
list[1..3]     //Result: [2, 3, 4] 
list[1..<3]    //Result: [2, 3] 
list + [6,7]   //Result: [1, 2, 3, 4, 5, 6, 7] 
list - [4,5,6] //Result: [1, 2, 3] 
list << 6      //Result: [1, 2, 3, 4, 5, 6] 
list << [6,7]  //Result: [1, 2, 3, 4, 5, 6, [6, 7]] 


list方法: 
[2,5].add(7)               //Result: true; list = [2, 5, 7] 
[2,5].add(1,9)             //list = [2, 7, 5] 
[2,5].add([7,9])           //Result: [2, 5, [7, 9]] 
[2, 5, [7, 9]].flatten()   //Result: [2, 5, 7, 9];克隆并解开下层list 
[2,5].get(1)               //Result: 5 
[2,5].size()               //Result: 2 
[2,5].isEmpty()            //Result: false 
[2,5].getAt(1)             //Result: 5 
[2,5,7].getAt(1..2)        //Result: [5, 7] 
[2,5,7].getAt(-1)          //Result: 7;get()不支持负数参数,getAt()支持 
[2,5,7].getAt([1,2])       //Result: [5, 7] 
[2,5,7].intersect([5,9,2]) //Result: [5, 2];交集 
[2,5,7].pop()              //Result: 7 
[2,5,7].plus([3,6])        //Result: [2, 5, 7, 3, 6] 
[2,5,7,2].minus(2)         //Result: [5, 7] 
[2,5,7].remove(1)          //Result: 5; list = [2, 7] 
[2,7,5].reverse()          //Result: [5, 7, 2] 
[2,7,5].sort()             //Result: [2, 5, 7] 
map类
// 变量定义:Map变量由[:]定义,比如
def aMap = ['key1':'value1','key2':true]
// Map由[:]定义,注意其中的冒号。冒号左边是key,右边是Value。
// key必须是字符串,value可以是任何对象。另外,key可以用''或""包起来,也可以不用引号包起来。比如
def aNewMap = [key1:"value",key2:true]
// 其中的key1和key2默认被处理成字符串"key1"和"key2"
// 不过Key要是不使用引号包起来的话,也会带来一定混淆,比如
def key1="wowo"
def aConfusedMap=[key1:"who am i?"]
// aConfuseMap中的key1到底是"key1"还是变量key1的值“wowo”?显然,答案是字符串"key1"。
// 如果要是"wowo"的话,则aConfusedMap的定义必须设置成:
def aConfusedMap=[(key1):"who am i?"]
// Map中元素的存取更加方便,它支持多种方法:
println aMap.keyName    // 这种表达方法好像key就是aMap的一个成员变量一样
println aMap['keyName'] // 这种表达方法更传统一点
aMap.anotherkey = "i am map"  // 为map添加新元素
map.put('height', '175')  //Result: ["name":"Bruce", "age":27, "weight":"60kg", 

map操作: 
def map = [3:56, 'name':'Bruce'] 
def a = 'name' 
map.name    //Result: "Bruce" 
map['name'] //Result: "Bruce" 
map[a]      //Result: "Bruce" 
map[3]      //Result: 56 
以下访问是错误的,会抛出异常 
map[name] 
map.3 

map方法: 
def map = ['name':'Bruce', 'age':27] 
map.containsKey('name')   //Result: true 
map.get('name')           //Result: "Bruce" 
map.get('weight', '60kg') //Result: "60kg";会把key:value加进去 
map.getAt('age')          //Result: 27 
map.keySet()              //Result: [name, age, weight] 
map.put('height', '175')  //Result: ["name":"Bruce", "age":27, "weight":"60kg", "height":"175"] 
map.values().asList()     //Result: ["Bruce", 27, "60kg", "175"] 
map.size()                //Result: 4 


map遍历
1、使用each方法
Students.each {
    def student ->
        println "the key is ${student.key} and the value is ${student.value}"
}
这种方式是根据Map集合中的Entry(键值对)进行遍历的,还可以根据key与value进行遍历,需要注意的是,key与value参数的顺序不能颠倒,否则会造成数据的错乱

// 直接遍历key, value而不再是遍历entry
Students.each { key, value -> 
    println "the key is ${key} and , the value is ${value}"
}
2、eachWithIndex方法
这个是带索引的遍历

// 带索引的each遍历
Students.eachWithIndex { def student, int index -> // 二者的顺序不能颠倒
    println "the index is ${index} , the key is ${student.key} , and the value is ${student.value}"
}
这个方法同样页可以使用key与value的方式进行带索引的map集合遍历,使用eachWithIndex方法,但是同样index必须为最后一个参数,否则会造成数据错乱

Students.eachWithIndex { def key, def value, int index -> // 三者的顺序不能颠倒
    println "the index is ${index} , the key is ${key} , and the value is ${value}"
}
range类
def aRange = 1..5 // <==Range类型的变量 由begin值+两个点+end值表示左边这个aRange包含1,2,3,4,5这5个值
//如果不想包含最后一个元素,则
def aRangeWithoutEnd = 1..<5  // 包含1,2,3,4这4个元素
循环
 def list = [1,2,3,4,5]
        for (int i in list){
            println i
        }

 while (n<5){
            n+=1
            println n
        }

 for (int i=0;i<5;i++){
            println i
        }

for(int i in 1..5) {
    println(i);
}

def employee = ["Ken" : 21, "John" : 25, "Sally" : 22]
for(emp in employee) {
    println(emp);
}   
#Ken = 21
#John = 25
#Sally = 22
数据类型转换
int类型--------->String类型
 
方式一:
int num = 100;
String s = "" + num;
方式二:
int num = 100;
String s = String.valueOf(num);
//String类下valueOf可将任何类型转换成String类型
方式三:
int num=100;
Integer in = new Integer(num);
String s= in.toString();
方式四:
int num=100;
String s = Integer.toString(num);
 
 
String类型--------->int类型
方式一:
String s = "100";
Integer in= new Integer(s);
//Integer类下将Integer转换成功int的方法
int num = in.intValue();
方式二:
String s=“100”;
int num = Integer.parseInt(s);
json对象处理
对象转Json
List转为Json和简单,只需要使用groovy.json包下的JsonOutput类即可
import groovy.json.JsonBuilder
imprt groovy.json.JsonOutput

def list = [new Person(name: 'YangHang', age: 25)
            , new Person(name: 'YangKunZe', age: 24)]

// 对象转成Json 两种方法
def json = JsonOutput.toJson(list)
def json = new JsonBuilder(list)


Json转对象
同理,我们需要使用groovy.json包下的JsonSlurper类即可

// Json转成对象
JsonSlurper jsonS = new JsonSlurper()
def l = jsonS.parseText(json) #json指json对象

原文链接:https://blog.csdn.net/qq_36929361/article/details/104242748
原文链接:https://blog.csdn.net/qq_38056514/article/details/127218578

相关文章

网友评论

      本文标题:Groovy基本语法

      本文链接:https://www.haomeiwen.com/subject/jivvjdtx.html