当前位置:网站首页>Groovy basic syntax collation
Groovy basic syntax collation
2022-07-06 20:03:00 【microhex】
Studying recently Gradle, So I'm sorting it out Gradle development language Groovy Basic grammar , For a rainy day :
List of articles
1. Grovvy And String
String Logic :
// Single quotation marks and java In the same
def name = 'Tom'
// Double quotes
def name2 = "Tom"
// Three quotes Original format
def name3 = ''' hello world '''
Define expressions
def sum = "$name${2+3}"
println sum
frequently-used String API
def string = "hello"
def string2 = "hello2"
// Compare
println string > string2
// take [m,n] The logic between
println string2[2,4]
// Subtraction [ Replace ]
println string - string
// The reverse
println string.reverse()
// title case
println string.capitalize()
// Whether there are numeric characters in the string
println string.isNumber()
2. Closure
1. Define parameterless closures
// Definition and use
// Parameterless closure
def closure = {
println "hello world"
}
// call 1
closure()
// call 2
closure.call()
2. Define parametric closures
// Closures with parameters
def closure = {
String name, int age ->
println "name: $name, age : $age"
}
closure.call("Tom",18)
// With default parameters
def closure2 = {
println "hello $it "
}
closure2.call("world")
3. The return value of the closure
def closure = {
println "hello ${it}"
return 120
}
def result = closure.call("Tom")
println result
4. Anonymous inline functions
// Anonymous inline functions
int x = fab(5)
static int fab(int num) {
int result = 1
1.upto(num) {
x -> result *= x }
return result
}
println x
5. String dependent Api
String str = "2 and 3 is 5"
// each Traverse
str.each {
s -> printf s * 2 }
// find Find the first character that matches the criteria
println str.find {
it.isNumber() }
// findAll Find all characters that match the criteria
println str.findAll{
!it.isNumber()}
// any Find out if there are any matching characters
println str.any {
it.isNumber() }
// every Find out whether all characters meet the conditions
println str.every {
it.isNumber()}
// Yes str The results of each individual operation of are saved in a set
def list = str.collect {
it.toUpperCase() }
println list
3. List aggregate
1. Definition List
// Definition List
def list = new ArrayList()
def arrayList = [1,2,3,4,5,6]
println list.class
println arrayList.class
// Define an array
def array = [1,2,3,4,5] as int[]
2. List The addition of
def arrayList = [1,2,3,4,5,6]
arrayList.add(3)
println arrayList
arrayList << 2
println arrayList
3. List The deletion of
def arrayList = [1,2,3,4,5,6]
// 1. Delete the object at the subscript position
arrayList.remove(2)
// 2. Delete object
arrayList.remove((Object)2)
// 3. Delete the qualified
arrayList.removeAll{
it % 2 == 0}
// 4. Using operators 【 Remove elements 1 and 2】
def result = arrayList -[1,2]
println result
4.List Common use of API
def arrayList = [1,2,3,4,5,6]
//1. The first data that meets the condition
def result = arrayList.find {
it == 2}
//2. All data that meet the conditions
def result2 = arrayList.findAll {
it % 2 == 1}
//3. Find whether the data meets the conditions
def result3 = arrayList.any{
it % 2 == 0}
//4. Find out whether all conditions are met
def result4 = arrayList.every{
it % 2 == 1}
//5. Find the maximum and minimum
def min = arrayList.min()
def max = arrayList.max {
Math.abs(it) }
//6. Statistics
def count = arrayList.count()
//7. Sort
arrayList.sort()
4. Map aggregate
The basic operation is :
//1. Definition Map
def colors = [red:'#F00', green : '#0F0', blue:'#00F']
println colors['red']
println colors.green
println colors.getClass()
//2. Add normal objects
colors.yellow = "#333"
// 3. Add collection object
colors += [hello:"hello", world:"world"]
println colors
//3. Map The traversal Use entry Object mode
colors.each {
println it.key + "--->>" + it.value
}
//4. Using key value pairs
colors.each {
key, value ->
println "key:$key" + "value:$value"
}
// 5. Traversal with index
colors.eachWithIndex {
Map.Entry<String, String> entry, int index ->
println index + "-" + entry.key + "-" + entry.value
}
//6. map Lookup
def result = colors.find {
it.key == 'red'}
println result
//7. findAll lookup
def result2 = colors.findAll {
it.value.startsWith("#")}
//8. nested queries
def result3 = colors.findAll {
it.value.startsWith("#")}.collect {
it.value.length() }
println result3
//9. Implement group query
def groupResult = colors.groupBy {
it -> it.key.length()}
println groupResult
//10. Sorting function
def sortResult = colors.sort {
t1, t2 -> t1.key > t2.key ? 1 : -1 }
println sortResult
5. Range Logic
// Definition
// 1. Range It's equivalent to a lightweight List
def range = 1..10
println range[0]
println range.contains(4)
println range.from
println range.to
// 2. Traverse
range.forEach{
println it
}
// 3. Another kind of traversal
for (i in range){
println i
}
def getRrade(Number score) {
def result
switch (score) {
case 0..<60:
result =" fail, "
break
case 60..<80:
result = " good "
break
case 80..100:
result = " good "
break
default:
result = " abnormal "
break
}
return result
}
println getRrade(90)
println getRrade(56)
println getRrade(-1)
6. File operations
//1. Traversal file
def file = new File("/Users/xinghe/Downloads/333.html")
file.eachLine {
println it
}
//2. Return all text
def text = file.getText()
println text
//3. With List<String> Return each line of the file
def lines = file.readLines()
println lines.toListString()
//4. With Java Read the contents of the file as a stream in
def reader = file.withReader {
reader ->
char[] buffer = new char[file.length()]
reader.read(buffer)
return buffer
}
println reader.toList()
//5. Write data
file.withWriter {
it.append("hello the end")
}
7. Json operation
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)
]
// General output
println JsonOutput.toJson(list)
// Format output
println JsonOutput.prettyPrint(JsonOutput.toJson(list))
// Json String to object
def JsonSlurper = new JsonSlurper()
def jsonObject = JsonSlurper.parseText("[{\"age\":20,\"name\":\"Tom\"},{\"age\":21,\"name\":\"Jetty\"},{\"age\":23,\"name\":\"Marry\"}]")
println jsonObject
// Get object properties directly
def object = JsonSlurper.parseText("{\"name\":\"Tom\"}")
println object.name
8. xml operation
1. XML analysis
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. analysis XML data
def xmlSluper = new XmlSlurper()
def result = xmlSluper.parseText(xmlString)
// To get the results
//1. obtain package The content of
println result[email protected]package
//2. obtain pre-content The content of
println result."pre-content".text().trim()
//3. obtain application Of name Property value
println result.application[email protected]'android:name'
println result.application[email protected]"android:theme"
// 4. Get the second Activity Of name name
println result.application.activity[1][email protected]'android:name'
//5. Traverse XML node
result.application.activity.each {
println it[email protected]'android:name'
}
2. XML Generate
/** * Generate XML Format data * <html> * <title id='123',name='android'>xml Generate * <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 Generate ') {
person('hello')
}
body(name:'java') {
activity(id:'001', class:'MainActivity','abc')
activity(id:'002', class:'SecondActivity','adf')
}
}
println sw
边栏推荐
- Vscode debug run fluent message: there is no extension for debugging yaml. Should we find yaml extensions in the market?
- 22-07-05 七牛云存储图片、用户头像上传
- BUUCTF---Reverse---easyre
- POJ1149 PIGS 【最大流量】
- 微信小程序常用集合
- Appx代码签名指南
- Wonderful coding [hexadecimal conversion]
- Guangzhou's first data security summit will open in Baiyun District
- 使用ssh连接被拒
- JVM_常见【面试题】
猜你喜欢

VMware virtual machine cannot open the kernel device "\.\global\vmx86"

Cesium Click to draw a circle (dynamically draw a circle)
腾讯字节等大厂面试真题汇总,网易架构师深入讲解Android开发
腾讯T4架构师,android面试基础

学习打卡web

Selenium advanced operations

【Yann LeCun点赞B站UP主使用Minecraft制作的红石神经网络】

Example of shutter text component

LeetCode_ Double pointer_ Medium_ 61. rotating linked list

蓝桥杯 微生物增殖 C语言
随机推荐
Systematic and detailed explanation of redis operation hash type data (with source code analysis and test results)
js实现力扣71题简化路径
AsyncHandler
Tensorflow2.0 self defined training method to solve function coefficients
【Yann LeCun点赞B站UP主使用Minecraft制作的红石神经网络】
mod_ WSGI + pymssql path SQL server seat
OceanBase社区版之OBD方式部署方式单机安装
从sparse.csc.csr_matrix生成邻接矩阵
[translation] linkerd's adoption rate in Europe and North America exceeded istio, with an increase of 118% in 2021.
精彩编码 【进制转换】
Web开发小妙招:巧用ThreadLocal规避层层传值
Learning and Exploration - Seamless rotation map
2022年6月语音合成(TTS)和语音识别(ASR)论文月报
HDU 1026 Ignatius and the Princess I 迷宫范围内的搜索剪枝问题
理解 YOLOV1 第二篇 预测阶段 非极大值抑制(NMS)
Blue Bridge Cup microbial proliferation C language
POJ1149 PIGS 【最大流量】
PowerPivot - DAX (first time)
句号压缩过滤器
22-07-05 七牛云存储图片、用户头像上传