https://github.com/zhan9dong/groovy-learning/blob/master/content/learninggroovy/
- 常用
# 列表操作findall,条件匹配的所有值
https://www.w3cschool.cn/groovy/groovy_findall.html
# collect(),为每个元素转换成新的值
https://www.w3cschool.cn/groovy/groovy_collect.html
#bool布尔相关
println 'test'.toBoolean() //false
println new Boolean('test') //false
println new Boolean('TruE') //true
println new Boolean('test'=='test') //true
- 模板
class Example {
static void main(String[] args) {
def lst = [1,2,3,4];
def value;
value = lst.find { it > 2}
//value = lst.find {element -> element > 2}
println(value);
}
}
- 闭包
# 1. JavaScript箭头函数
var funcName = (params) => params + 2
# 2. groovy闭包
//执行一句话
{ printf 'Hello World' }
//闭包有默认参数it,且不用申明
{ println it }
//闭包有默认参数it,申明了也无所谓
{ it -> println it }
// name是自定义的参数名
{ name -> println name }
//多个参数的闭包
{ String x, int y ->
println "hey ${x} the value is ${y}"
}
//groovy.lang.Closure对象
def xxx = { params -> code } //或者 def xxx={code}
def innerClosure = {
printf("hello")
}
# 闭包
def hello = { String x ->
printf("hello ${x}")
}
# 函数
def a(arg = 'abc'){
println(arg)
}
//函数
def find(list, tester) {
for (item in list)
if (tester(item)) return item
}
//调用,两种方式都行,闭包形式传参
println find([3,3,4,1,2,0,1,23232,2],{ it > 1 });
println find([3,3,4,1,2,0,1,23232,2]){ it > 1 }
// 闭包
def concat = { x, y -> return x + y }
def burn = concat.curry("burn");
println burn('wood')
# 定义list每个元素是整数类型
List<Integer> nums = [1, 2, 3.1415, 'pie']
- 常用
//用闭包定义一个方法 var1为参数 ,->后面是执行语句(当然参数不是必须的)
def methodA={var1-> print "this is methodA"}
//用闭包定义一个方法 var1为参数 ,->后面是执行语句(当然参数不是必须的)
def methodB={var1-> print "this is methodB"}
String.metaClass.addMethodA=methodA; //将methodA绑定为成员方法。
String.metaClass.'static'.addMethodB=methodB; //将methodB绑定为静态方法
String s="str";
s.addMethodA('good'); //实例调用方法A
String.addMethodB('hello'); //静态类调用方法B
?。是一个空安全运算符,用于避免意外的NPE。
if ( a?.b ) { .. }
和…一样
if ( a != null && a.b ) { .. }
?三元运算
1. 正常
if(!expired){
println 'expired is null'
return true
}
else if(now.after(expired)){
println 'cache has expired'
return true
}
else
return false
2. 三元
2.0 简单
def res1 = '11' ?: '33' //11
def res2 = '11' ? '22': '33' //22
def res3 = false ? '22': '33' //33
2.1
def expired= false, expired2= true
return (!expired2) ?
{println "expired is null"; true}() : (expired2) ? {println "cache has expired"; true}() : false
2.2
def test = (expired) ? 'test1': (!expired2) ? 'test2' : 'test3'
println (test)
循环
(1..10).each { println(it)}
for (def i in 1..100){
println(i)
}
(1..<5).each { println(it) }
# map语法糖
def foo = 1
def bar = 2
def map = [(foo): bar]
println map //[1:2]
println map.foo //null
println map[foo] //2
- 正则
def email = "909253305@qq.com"
def isEmail = email ==~ /[w.]+@[w.]+/
println(isEmail);
email = 'mailto:adam@email.com'
def mr = email =~ /([w.]+)@[w.]+/;
if (mr.find()){
println mr.group();
println mr.group(1)//分组结果
}
# 列表操作findAll
def jobNames = getJobNames()
def matchjobs = jobNames.findAll{ name -> name =~ /(test)w*/ }
- groovy设计模式
https://github.com/zhan9dong/groovy-learning/blob/master/content/learninggroovy/charpter6.md
# 策略模式
假设有三个方法
def totalPricesLessThan10(prices) {
int total = 0
for (int price : prices)
if (price < 10) total += price
total
}
def totalPricesMoreThan10(prices) {
int total = 0
for (int price : prices)
if (price > 10) total += price
total
}
def totalPrices(prices) {
int total = 0
for (int price : prices)
total += price
total
}
以上三个方法重复很多,并且它们处理模型是一样,我们可以考虑用策略模式重写,
//1. 首先定义处理总的入口
def totalPrices(prices, selector) {
int total = 0
for (int price : prices)
if (selector(price)) total += price
total
}
//2.传入不同的策略处理
println totalPrices([1,2,3,4,5,6,7,8,9,10]) { it < 10 }
//println totalPrices([1,2,3,4,5,6,7,8,9,10], { it < 10 })
println totalPrices([1,2,3,4,5,6,7,8,9,10,11,12]) { it > 10 }
println totalPrices([1,2,3,4,5]) { true }
- 函数式编程
class Person {
String name;
int age
}
def persons = [
new Person(name: 'Bob', age: 20),
new Person(name: 'A', age: 15),
new Person(name: 'D', age: 10)
]
println persons.collect { person -> person.name };
println persons.findAll { person -> person.age >= 18 }
println persons.inject(0) {total,p -> total + p.age}
println persons[0..1]
def a = [1, 2, 3]
def b = [4, 5]
println a + b
// Result: [1, 2, 3, 4, 5]
批量截取字符串操作的实例
def list = ['foo', 'bar']
def newList = []
list.collect(newList) { it.substring(1) };
println newList // [oo, ar]