当前位置:网站首页>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
边栏推荐
- Crawler (14) - scrape redis distributed crawler (1) | detailed explanation
- Pay attention to the partners on the recruitment website of fishing! The monitoring system may have set you as "high risk of leaving"
- How to handle the timeout of golang
- Qinglong panel white screen one key repair
- Poj3617 best cow line
- Node.js: express + MySQL实现注册登录,身份认证
- Cesium 两点之间的直线距离
- 【计网】第三章 数据链路层(3)信道划分介质访问控制
- 腾讯云数据库公有云市场稳居TOP 2!
- New generation garbage collector ZGC
猜你喜欢
[infrastructure] deployment and configuration of Flink / Flink CDC (MySQL / es)
Information System Project Manager - Chapter VIII project quality management
An East SMS login resurrection installation and deployment tutorial
企业精益管理体系介绍
5. 無線體內納米網:十大“可行嗎?”問題
Standardized QCI characteristics
OceanBase社区版之OBD方式部署方式单机安装
语音识别(ASR)论文优选:全球最大的中英混合开源数据TALCS: An Open-Source Mandarin-English Code-Switching Corpus and a Speech
redisson bug分析
PowerPivot——DAX(初识)
随机推荐
JVM_常见【面试题】
The "white paper on the panorama of the digital economy" has been released with great emphasis on the digitalization of insurance
【计网】第三章 数据链路层(4)局域网、以太网、无线局域网、VLAN
青龙面板白屏一键修复
腾讯云数据库公有云市场稳居TOP 2!
Web开发小妙招:巧用ThreadLocal规避层层传值
精彩编码 【进制转换】
腾讯T4架构师,android面试基础
Leetcode 30. Concatenate substrings of all words
LeetCode_ Gray code_ Medium_ 89. Gray code
Cesium Click to draw a circle (dynamically draw a circle)
PHP and excel phpexcel
小微企业难做账?智能代账小工具快用起来
Poj3617 best cow line
颜色(color)转换为三刺激值(r/g/b)(干股)
Alibaba数据源Druid可视化监控配置
企业精益管理体系介绍
Learn to explore - use pseudo elements to clear the high collapse caused by floating elements
【Yann LeCun点赞B站UP主使用Minecraft制作的红石神经网络】
AsyncHandler