当前位置:网站首页>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
边栏推荐
- 腾讯云数据库公有云市场稳居TOP 2!
- Guangzhou's first data security summit will open in Baiyun District
- Poj3617 best cow line
- Systematic and detailed explanation of redis operation hash type data (with source code analysis and test results)
- 1805. Number of different integers in the string
- OceanBase社区版之OBD方式部署方式单机安装
- [translation] linkerd's adoption rate in Europe and North America exceeded istio, with an increase of 118% in 2021.
- POJ 3207 Ikki&#39;s Story IV – Panda&#39;s Trick (2-SAT)
- golang的超时处理使用技巧
- 【计网】第三章 数据链路层(4)局域网、以太网、无线局域网、VLAN
猜你喜欢
Hudi vs Delta vs Iceberg
Learn to explore - use pseudo elements to clear the high collapse caused by floating elements
[play with Linux] [docker] MySQL installation and configuration
Leetcode 30. Concatenate substrings of all words
Node.js: express + MySQL实现注册登录,身份认证
Classic 100 questions of algorithm interview, the latest career planning of Android programmers
5. 無線體內納米網:十大“可行嗎?”問題
Li Kou 101: symmetric binary tree
Selenium advanced operations
(3) Web security | penetration testing | basic knowledge of network security construction, IIS website construction, EXE backdoor generation tool quasar, basic use of
随机推荐
Tencent Android development interview, basic knowledge of Android Development
数据的同步为每个站点创建触发器同步表
Understand yolov1 Part II non maximum suppression (NMS) in prediction stage
Poj1149 pigs [maximum flow]
某东短信登录复活 安装部署教程
Cf960g - bandit Blues (type I Stirling number +ogf)
Tensorflow2.0 self defined training method to solve function coefficients
(3) Web security | penetration testing | basic knowledge of network security construction, IIS website construction, EXE backdoor generation tool quasar, basic use of
腾讯T3手把手教你,真的太香了
2022年6月语音合成(TTS)和语音识别(ASR)论文月报
121. The best time to buy and sell stocks
String长度限制?
After solving 2961 user feedback, I made such a change
121. 买卖股票的最佳时机
AsyncHandler
22-07-05 七牛云存储图片、用户头像上传
Redisson bug analysis
golang的超时处理使用技巧
腾讯T4架构师,android面试基础
Alibaba数据源Druid可视化监控配置