当前位置:网站首页>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
边栏推荐
- Poj1149 pigs [maximum flow]
- 广州首个数据安全峰会将在白云区开幕
- Social recruitment interview experience, 2022 latest Android high-frequency selected interview questions sharing
- Teach you to learn JS prototype and prototype chain hand in hand, a tutorial that monkeys can understand
- MySQL information schema learning (II) -- InnoDB table
- String length limit?
- mod_ WSGI + pymssql path SQL server seat
- OceanBase社区版之OBD方式部署方式单机安装
- 腾讯安卓开发面试,android开发的基础知识
- 2022年6月语音合成(TTS)和语音识别(ASR)论文月报
猜你喜欢

Transformer model (pytorch code explanation)
腾讯架构师首发,2022Android面试笔试总结

Speech recognition (ASR) paper selection: talcs: an open source Mandarin English code switching corps and a speech

5. 无线体内纳米网:十大“可行吗?”问题

腾讯T3手把手教你,真的太香了

Learn to explore - use pseudo elements to clear the high collapse caused by floating elements

某东短信登录复活 安装部署教程

5. 無線體內納米網:十大“可行嗎?”問題

Configuration and simple usage of the EXE backdoor generation tool quasar

Leetcode 30. Concatenate substrings of all words
随机推荐
Phoenix Architecture 3 - transaction processing
小微企业难做账?智能代账小工具快用起来
Blue Bridge Cup microbial proliferation C language
Poj1149 pigs [maximum flow]
蓝桥杯 微生物增殖 C语言
Guangzhou's first data security summit will open in Baiyun District
121. The best time to buy and sell stocks
PHP与EXCEL PHPExcel
【云原生与5G】微服务加持5G核心网
腾讯T2大牛亲自讲解,跳槽薪资翻倍
How to handle the timeout of golang
5. 無線體內納米網:十大“可行嗎?”問題
Classic 100 questions of algorithm interview, the latest career planning of Android programmers
From spark csc. csr_ Matrix generate adjacency matrix
Standardized QCI characteristics
MySql必知必会学习
MySQL information schema learning (II) -- InnoDB table
leetcode先刷_Maximum Subarray
Method keywords deprecated, externalprocname, final, forcegenerate
Recursive implementation of department tree