当前位置:网站首页>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
边栏推荐
- redisson bug分析
- Tensorflow2.0 self defined training method to solve function coefficients
- 学习打卡web
- Microservice architecture debate between radical technologists vs Project conservatives
- Cesium 点击绘制圆形(动态绘制圆形)
- Selenium advanced operations
- 案例 ①|主机安全建设:3个层级,11大能力的最佳实践
- MySql必知必会学习
- After solving 2961 user feedback, I made such a change
- 精彩编码 【进制转换】
猜你喜欢
Standardized QCI characteristics
HMS Core 机器学习服务打造同传翻译新“声”态,AI让国际交流更顺畅
深入浅出,面试突击版
Learning and Exploration - Seamless rotation map
力扣101题:对称二叉树
Tencent T2 Daniel explained in person and doubled his job hopping salary
After solving 2961 user feedback, I made such a change
(3) Web security | penetration testing | basic knowledge of network security construction, IIS website construction, EXE backdoor generation tool quasar, basic use of
It's enough to read this article to analyze the principle in depth
腾讯T2大牛亲自讲解,跳槽薪资翻倍
随机推荐
Method keywords deprecated, externalprocname, final, forcegenerate
POJ 3207 Ikki&#39; s Story IV – Panda&#39; s Trick (2-SAT)
数据的同步为每个站点创建触发器同步表
Configuration and simple usage of the EXE backdoor generation tool quasar
小微企业难做账?智能代账小工具快用起来
js实现力扣71题简化路径
[play with Linux] [docker] MySQL installation and configuration
Analysis of rainwater connection
MySql必知必会学习
【云原生与5G】微服务加持5G核心网
腾讯字节阿里小米京东大厂Offer拿到手软,老师讲的真棒
深度剖析原理,看完这一篇就够了
LeetCode_ Gray code_ Medium_ 89. Gray code
社招面试心得,2022最新Android高频精选面试题分享
Social recruitment interview experience, 2022 latest Android high-frequency selected interview questions sharing
Introduction to enterprise lean management system
某东短信登录复活 安装部署教程
腾讯云数据库公有云市场稳居TOP 2!
Example of shutter text component
【计网】第三章 数据链路层(4)局域网、以太网、无线局域网、VLAN