当前位置:网站首页>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
边栏推荐
- 腾讯字节阿里小米京东大厂Offer拿到手软,老师讲的真棒
- 力扣101题:对称二叉树
- Learning and Exploration - function anti shake
- Interpretation of Dagan paper
- A5000 vGPU显示模式切换
- LeetCode_ Gray code_ Medium_ 89. Gray code
- 1805. Number of different integers in the string
- Configuration and simple usage of the EXE backdoor generation tool quasar
- 腾讯安卓开发面试,android开发的基础知识
- Example of shutter text component
猜你喜欢
BUUCTF---Reverse---easyre
Learning and Exploration - Seamless rotation map
【翻译】云原生观察能力微调查。普罗米修斯引领潮流,但要了解系统的健康状况仍有障碍...
社招面试心得,2022最新Android高频精选面试题分享
Tencent Android interview must ask, 10 years of Android development experience
《数字经济全景白皮书》保险数字化篇 重磅发布
LeetCode_ Double pointer_ Medium_ 61. rotating linked list
Monthly report of speech synthesis (TTS) and speech recognition (ASR) papers in June 2022
MySQL information schema learning (I) -- general table
企业精益管理体系介绍
随机推荐
Monthly report of speech synthesis (TTS) and speech recognition (ASR) papers in June 2022
微信小程序常用集合
语音识别(ASR)论文优选:全球最大的中英混合开源数据TALCS: An Open-Source Mandarin-English Code-Switching Corpus and a Speech
Poj1149 pigs [maximum flow]
mod_wsgi + pymssql通路SQL Server座
Systematic and detailed explanation of redis operation hash type data (with source code analysis and test results)
新一代垃圾回收器—ZGC
LeetCode_ Double pointer_ Medium_ 61. rotating linked list
POJ 3207 Ikki&#39;s Story IV – Panda&#39;s Trick (2-SAT)
句号压缩过滤器
Understand yolov1 Part II non maximum suppression (NMS) in prediction stage
A5000 vGPU显示模式切换
MySQL information schema learning (I) -- general table
HMS Core 机器学习服务打造同传翻译新“声”态,AI让国际交流更顺畅
案例 ①|主机安全建设:3个层级,11大能力的最佳实践
LeetCode_ Gray code_ Medium_ 89. Gray code
【基础架构】Flink/Flink-CDC的部署和配置(MySQL / ES)
【翻译】供应链安全项目in-toto移至CNCF孵化器
系统与应用监控的思路和方法
Microservice architecture debate between radical technologists vs Project conservatives