当前位置:网站首页>Groovy基础语法整理
Groovy基础语法整理
2022-07-06 12:10:00 【microhex】
最近在学习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[email protected]package
//2. 获取pre-content的内容
println result."pre-content".text().trim()
//3. 获取application的name属性值
println result.application[email protected]'android:name'
println result.application[email protected]"android:theme"
// 4. 获取第二个Activity的name名称
println result.application.activity[1][email protected]'android:name'
//5. 遍历XML节点
result.application.activity.each {
println it[email protected]'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
边栏推荐
- 颜色(color)转换为三刺激值(r/g/b)(干股)
- From spark csc. csr_ Matrix generate adjacency matrix
- 新一代垃圾回收器—ZGC
- 算法面试经典100题,Android程序员最新职业规划
- logstash高速入口
- 技术分享 | 抓包分析 TCP 协议
- MySQL information schema learning (I) -- general table
- [infrastructure] deployment and configuration of Flink / Flink CDC (MySQL / es)
- 腾讯T4架构师,android面试基础
- Phoenix Architecture 3 - transaction processing
猜你喜欢
随机推荐
技术分享 | 抓包分析 TCP 协议
手把手教你学会js的原型与原型链,猴子都能看懂的教程
Introduction to enterprise lean management system
爬虫(14) - Scrapy-Redis分布式爬虫(1) | 详解
小微企业难做账?智能代账小工具快用起来
Yyds dry goods inventory leetcode question set 751 - 760
mod_wsgi + pymssql通路SQL Server座
Swiftui game source code Encyclopedia of Snake game based on geometryreader and preference
Tencent T2 Daniel explained in person and doubled his job hopping salary
[infrastructure] deployment and configuration of Flink / Flink CDC (MySQL / es)
激进技术派 vs 项目保守派的微服务架构之争
Cesium 两点之间的直线距离
Wonderful coding [hexadecimal conversion]
[translation] micro survey of cloud native observation ability. Prometheus leads the trend, but there are still obstacles to understanding the health of the system
350. Intersection of two arrays II
Alibaba data source Druid visual monitoring configuration
Systematic and detailed explanation of redis operation hash type data (with source code analysis and test results)
Appx代码签名指南
logstash高速入口
MySQL must know and learn