Groovy入门-闭包

由{}包围起来的代码块就是闭包
println {}//执行改行,结果:类名.ClosureDemo runclosure1@10a2d64 匿名内部类@hash_code
结论一:闭包是一个匿名内部类的对象
也可以给闭包取名字:
def aClosure = {
println ‘Hello Closure!’
}
println aClosure //结果:类名$_run_closure2@89cf1e

调用闭包

aClosure.call() //使用call()调用闭包
aClosure() //调用闭包的简写方式,类似于方法调用
结论二:闭包是一个可执行的代码块
闭包在调用的时候才会执行
参数化闭包:
def bClosure = {
println “Hello ${it}!”
}
bClosure.call(‘lxt008’)
bClosure(‘lxt008’)
bClosure ‘lxt008’
it是闭包的单个隐含参数

闭包参数

闭包使用显示参数
def cClosure = { name.address ->
println “ name, {address}!”
}
cClosure(‘lxt008’,’shenzhen’) //输出:lxt008,shenzhen!

闭包支持默认参数
def dClosure = { name,address=’shenzhen’ ->
println “ name, {address}!”
}
dClosure(‘lxt008’) //输出: lxt008,shenzhen

闭包作用域
def name = ‘lxt008’
def eClosure = { println name }
eClosure() //输出:lxt008

//闭包可以作为方法的参数
def aMethod(Closure closure){
name = ‘lxt007’; closure()
}
aMethod(eClosure) //输出:lxt008

def fClosure = {
name = ‘lxt006’; eClosure()
}
fClosure() //输出:lxt006

闭包可以返回值

def gClosure = { number ->
return number*2
}
println gClosure(3) //6 return 可省略

闭包与集合、字符串

闭包在Groovy中频繁出现,但最常见用于对一系列值上迭代,如列表、映射、范围、String、File
闭包可以用更简洁的方式对集合进行迭代,已经不需要Java的迭代器了。

用each遍历list

def citysList = ['shenzhen','beijing','shanghai']
citysList.each{ city->
    println city + ' '
}                                   //shenzhen beijing shanghai

遍历Map,Range,GString

遍历Map:

def citysMap = [1:'shenzhen',2:'beijing',3:'shanghai']
citysMap.each{ city->
    println city.key + ' ' + city.value + ' '
}                                  //1 shenzhen 2 beijing 3 shanghai

遍历Range:

(1..<5)each{ println it + '-' }   //1-2-3-4-

遍历GString

'lxt008'.each{ println it + '-' } //1-x-t-0-0-8- 

闭包为参数的迭代集合的方法
boolean ang(Closure clos) 有一个集合元素满足闭包条件则返回true
List collect(Closure clos) 把集合每个元素用闭包转换后放到coll中
List collect(Collection coll, Closure clos) 把集合每个元素用闭包转换后放到coll中
boolean every(Closure clos) 判断是否每个元素都满足闭包条件
Object find(Closure clos) 从集合中找到满足闭包条件的第一个元素
List findAll(Closure clos) 从集合中找到满足闭包条件的所有元素
int findIndexOf(Closure clos) 从集合中找到满足闭包条件的第一个元素的索引
Object inject(Object value, Closure clos)value与第一个元素传给闭包,结果值与第二个元素有传给闭包,类推。
void reverseEach(Closure clos) 反向迭代
List sort(Closure clos) 排序集合

find()方法

def value = [1,3,5,7,9].find{ element -> element > 6}
println "Found: ${value}"               //Found:7
value = [1,3,5,7,9].find{ element -> element > 10}
println "Found: ${value}"               //Found:null
value = ['Java':21,'Groovy':22,'Grails':25].find{ lang-> lang.value > 21 }
println "Found: ${value}"               //Found:Groovy=22

findAll()方法

def values = [1,3,5,7,9].findAll{ element -> element > 6 }
values.each{ println it}                     //7 9
[1,3,5,7,9].findAll{ element -> element > 6}.each{ println it }        //7 9
values = ['Java':21,'Groovy':22,'Grails':25].findAll{ lang -> lang.value > 21 }     //Grails=25 Groovy=22

any()与every()

println '===================================='
def anyElement = [11,12,13,14].any{ element -> element > 12 }
println "anyElement:${anyElement}"                  //anyElement:true
def allElements = [11,12,13,14].every{ element -> element > 10 }
println "allElement:${allElements}"                 //allElements:true
def anyLang = ['java':21,'Groovy':22,'Grails':25].any{ lang -> lang.value > 30 }
println "anyLang:${anyLang}"                        //anyLang:false
println '==================================='

collect()方法

def list = [1,2,3,4].collect{element -> return element * element}
println "List: ${list}"                    //return 可以省略 输出:List:[1,4,9,16]
list = (0..5).collect{ element -> 2* element }
println "list:${list}"                     //结果输出:list:[0,2,4,6,8]
def lang = ['Java':21,'Groovy':22,'Grails':25]
list = lang.collect{ entry -> ++ entry.value }
def olderLang = lang.collect{ entry -> ++entry.value; return entry}
println "lang:${lang}"                     //lang:["Java":23,"Groovy":24,"Grails":27]
println "list:${list}"                     //list:[22,23,26]
println "olderLang:${olderLang}"           //olderLang:[Java=23,Groovy=24,Grails=27]

inject()方法求阶乘

def numList = [2,3,4,5]
factorial = numList.inject(1){ previous, element -> previous * element}
println "Factorial(5):${factorial}"           //输出:Factorial(5):120
numList = [2,3,4,5]
closure = { previous, element -> previous * element }
factorial = numList.inject(1,closure)
println "Factorial(5):${factorial}"           //输出:Factorial:120

闭包的其他特性

//闭包可以嵌套
def outerClosure = { country->
    println country
    //嵌套定义闭包,方法则不允许
    def innerClosure = { city->
        println city
    }
    innerClosure('shenzhen')
}
outerClosure('china')                    //先打印china,后打印shenzhen
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页