class Example {
static void main(String[] args) {
def clos = {println "Hello World"};
clos.call();
}
}
闭包可以在定义闭包时引用变量,可以接受变量和参数:
class Example {
static void main(String[] args) {
def str1 = "Hello";
def clos = {param -> println "${str1} ${param}"}
clos.call("World");
// We are now changing the value of the String str1 which is referenced in the closure
str1 = "Welcome";
clos.call("World");
}
}
闭包可以作为方法的参数。
class Example {
def static Display(clo) {
// This time the $param parameter gets replaced by the string "Inner"
clo.call("Inner");
}
static void main(String[] args) {
def str1 = "Hello";
def clos = { param -> println "${str1} ${param}" }
clos.call("World"); // Hello World
// We are now changing the value of the String str1 which is referenced in Z str1 = "Welcome";
clos.call("World"); // Welcome World
// Passing our closure to a method
Example.Display(clos); //Welcome Inner
}
}
List,Map,String有方法可以接受闭包作为参数。
列表的each方法可以接受闭包作为参数,并将闭包应用于每一个元素。
class Example {
static void main(String[] args) {
def lst = [11, 12, 13, 14];
lst.each {println it}
}
}
Mao的each方法可以接受闭包作为参数,并将闭包应用于每一个元素。
class Example {
static void main(String[] args) {
def mp = ["TopicName" : "Maps", "TopicDescription" : "Methods in Maps"]
mp.each {println it}
mp.each {println "${it.key} maps to: ${it.value}"}
}
}
通过闭包可以很方便的使用闭包中的条件语句对元素进行筛选。
class Example {
static void main(String[] args) {
def lst = [1,2,3,4];
lst.each {println it}
println("The list will only display those numbers which are divisible by 2")
lst.each{num -> if(num % 2 == 0) println num}
}
}
闭包本身提供了一些方法:
方法 | 描述 |
---|---|
Object find(Closure closure) | 找到集合中与条件匹配的第一个值 |
List findAll(Closure closure) | 找到对象中与条件匹配的所有值 |
boolean any(Closure closure) boolean every(Closure closure) | 方法any迭代集合的每个元素,检查布尔谓词是否对至少一个元素有效。方法every检查是否对每一个元素有效 |
List collect(Closure closure) | 迭代使用闭包作为转换器将每个元素转换为新的值 |