Groovy基础语法整理

最近在学习Gradle,所以在整理一下Gradle开发语言Groovy基础语法,以备不时之需:

1. Grovvy之String

String逻辑:

// 单引号 和java中一样
def name = 'Tom'

// 双引号
def name2 = "Tom"

// 三引号 原始格式
def name3 = '''
        hello
        world 
'''

定义表达式

def sum = "$name${2+3}"
println sum

常用的String API

def string = "hello"
def string2 = "hello2"

// 比较
println string > string2

// 取 [m,n]之间的逻辑
println string2[2,4]

// 减法[替换]
println string - string

// 逆序
println string.reverse()

// 首字母大写
println string.capitalize()

// 字符串中是否为数字字符
println string.isNumber()


2. 闭包

1.定义无参数闭包

// 定义与使用
// 无参数的闭包
def closure = {
    
    
    println "hello world"
}

//调用1
closure()

//调用2
closure.call()

2.定义有参数闭包

// 带有参数的闭包
def closure = {
    
     String name, int age ->
    println "name: $name, age : $age"
}

closure.call("Tom",18)

// 带默认参数
def closure2 = {
    
    
    println "hello $it "
}

closure2.call("world")

3. 闭包的返回值

def closure = {
    
    
    println "hello ${it}"
    return 120
}

def result = closure.call("Tom")
println result

4. 匿名内联函数

// 匿名内联函数
int x = fab(5)

static int fab(int num) {
    
    
    int result = 1
    1.upto(num) {
    
     x -> result *= x }
    return result
}

println x

5. String 相关的Api

String str = "2 and 3 is 5"
// each 遍历
str.each {
    
     s -> printf s * 2 }

// find 查找符合条件的第一个字符
println str.find {
    
     it.isNumber() }

// findAll 查找符合条件的所有字符
println str.findAll{
    
     !it.isNumber()}

// any 查找是否存在符合条件的字符
println str.any {
    
     it.isNumber() }

// every 查找是否所有字符都符合条件
println str.every {
    
     it.isNumber()}

// 对str的每一位单独操作后的结果保存到一个集合中
def list = str.collect {
    
     it.toUpperCase() }
println list

3. List集合

1.定义List

// 定义List
def list = new ArrayList()
def arrayList = [1,2,3,4,5,6]
println list.class
println arrayList.class

// 定义数组
def array = [1,2,3,4,5] as int[]

2. List的添加

def arrayList = [1,2,3,4,5,6]

arrayList.add(3)
println arrayList

arrayList << 2
println arrayList

3. List的删除

def arrayList = [1,2,3,4,5,6]

// 1. 删除下标位置的对象
arrayList.remove(2)

// 2. 删除对象
arrayList.remove((Object)2)

// 3. 删除符合条件的
arrayList.removeAll{
    
     it % 2 == 0}

// 4. 使用操作符 【删除元素1和2】
def result = arrayList -[1,2]

println result

4.List的常用API

def arrayList = [1,2,3,4,5,6]

//1. 满足条件的第一个数据
def result = arrayList.find {
    
    it == 2}

//2. 满足条件的所有数据
def result2 = arrayList.findAll {
    
     it % 2 == 1}

//3. 查找是否满足条件的数据
def result3 = arrayList.any{
    
     it % 2 == 0}

//4. 查找是否全部满足条件
def result4 = arrayList.every{
    
     it % 2 == 1}

//5. 查找最大值和最小值
def min = arrayList.min()
def max = arrayList.max {
    
     Math.abs(it) }

//6. 统计
def count = arrayList.count()

//7. 排序
arrayList.sort()

4. Map集合

基本操作为:

//1. 定义Map
def colors = [red:'#F00', green : '#0F0', blue:'#00F']
println colors['red']
println colors.green
println colors.getClass()

//2. 添加普通对象
colors.yellow = "#333"

// 3. 添加集合对象
colors += [hello:"hello", world:"world"]
println colors

//3. Map的遍历 使用entry对象方式
colors.each {
    
    
    println it.key + "--->>" + it.value
}

//4. 用键值对的方式
colors.each {
    
     key, value ->
    println "key:$key" + "value:$value"
}

// 5. 带索引方式的遍历
colors.eachWithIndex {
    
     Map.Entry<String, String> entry, int index ->
    println index + "-" + entry.key + "-" + entry.value
}

//6. map的查找
def result = colors.find {
    
     it.key == 'red'}
println result

//7. findAll查找
def result2 = colors.findAll {
    
     it.value.startsWith("#")}

//8. 嵌套查询
def result3 = colors.findAll {
    
     it.value.startsWith("#")}.collect {
    
     it.value.length() }
println result3

//9.实现分组查询
def groupResult = colors.groupBy {
    
     it -> it.key.length()}
println groupResult

//10. 排序功能
def sortResult = colors.sort {
    
     t1, t2 -> t1.key > t2.key ? 1 : -1 }
println sortResult

5. Range 逻辑

// 定义
// 1. Range相当于一个轻量级的List
def range = 1..10
println range[0]
println range.contains(4)
println range.from
println range.to

// 2. 遍历
range.forEach{
    
    
    println it
}

// 3. 另外一种遍历
for (i in range){
    
    
    println i
}

def getRrade(Number score) {
    
    
    def result
    switch (score) {
    
    
        case 0..<60:
            result ="不及格"
            break
        case 60..<80:
            result = "良好"
            break
        case 80..100:
            result = "优秀"
            break
        default:
            result = "异常"
            break
    }

    return result
}

println getRrade(90)
println getRrade(56)
println getRrade(-1)

6. 文件操作

//1. 遍历文件
def file = new File("/Users/xinghe/Downloads/333.html")
file.eachLine {
    
    
    println it
}

//2. 返回所有文本
def text = file.getText()
println text

//3. 以List<String>返回文件的每一行
def lines = file.readLines()
println lines.toListString()

//4. 以Java中的流的方式读取文件内容
def reader = file.withReader {
    
     reader ->
    char[] buffer = new char[file.length()]
    reader.read(buffer)
    return buffer
}
println reader.toList()

//5. 写入数据
file.withWriter {
    
    
    it.append("hello the end")
}

7. Json操作

import groovy.json.JsonOutput
import groovy.json.JsonSlurper

def list = [
        new Person(name:"Tom", age:20),
        new Person(name:"Jetty", age:21),
        new Person(name: "Marry",age: 23)
]

// 一般输出
println JsonOutput.toJson(list)

// 格式化输出
println JsonOutput.prettyPrint(JsonOutput.toJson(list))

// Json字符串转成对象
def JsonSlurper = new JsonSlurper()
def jsonObject = JsonSlurper.parseText("[{\"age\":20,\"name\":\"Tom\"},{\"age\":21,\"name\":\"Jetty\"},{\"age\":23,\"name\":\"Marry\"}]")
println jsonObject

// 直接获取对象属性
def object = JsonSlurper.parseText("{\"name\":\"Tom\"}")
println object.name

8. xml操作

1. XML解析

final String xmlString = """
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.xing.demo">

    <pre-content>
        hello world
    </pre-content>
    
    <application
        android:name=".App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.BTTool.NoActionBar">

        <activity
            android:name=".ui.MainActivityUI"
            android:launchMode="singleTask"
            android:theme="@style/WelcomeTheme">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <activity android:name=".SecondActivityUI" />
        
     
    </application>
    
    </manifest>

"""
//1. 解析XML数据
def xmlSluper = new XmlSlurper()
def result = xmlSluper.parseText(xmlString)
// 获取结果
//1. 获取package的内容
println result.@package

//2. 获取pre-content的内容
println result."pre-content".text().trim()

//3. 获取application的name属性值
println result.application.@'android:name'
println result.application.@"android:theme"

// 4. 获取第二个Activity的name名称
println result.application.activity[1].@'android:name'

//5. 遍历XML节点
result.application.activity.each {
    
    
    println it.@'android:name'
}

2. XML生成

/**
 * 生成XML格式数据
 * <html>
 *     <title id='123',name='android'>xml生成
 *          <person>hello</person>
 *     </title>
 *     <body name='java'>
 *         <activity id='001' class='MainActivity'>abc</activity>
 *         <activity id='002' class='SecActivity'>abc</activity>
 *     </body>
 * </html>
 */
def sw = new StringWriter()
def xmlBuilder = new MarkupBuilder(sw)
xmlBuilder.html() {
    
    
    title(id:'12', name:'android', 'xml生成') {
    
    
        person('hello')
    }

    body(name:'java') {
    
    
        activity(id:'001', class:'MainActivity','abc')
        activity(id:'002', class:'SecondActivity','adf')
    }
}

println sw

猜你喜欢

转载自blog.csdn.net/u013762572/article/details/125343979