Groovy 闭包


当前第2页 返回上一页

以下示例显示如何将闭包作为参数发送到方法。

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");
		
      // We are now changing the value of the String str1 which is referenced in the closure
      str1 = "Welcome";
      clos.call("World");
		
      // Passing our closure to a method
      Example.Display(clos);
   } 
}

在上述示例中,

  • 我们定义一个名为Display的静态方法,它将闭包作为参数。

  • 然后我们在我们的main方法中定义一个闭包,并将它作为一个参数传递给我们的Display方法。

当我们运行上面的程序,我们将得到以下结果 -

Hello World 
Welcome World 
Welcome Inner

集合和字符串中的闭包

几个List,Map和String方法接受一个闭包作为参数。让我们看看在这些数据类型中如何使用闭包的例子。

使用闭包和列表

以下示例显示如何使用闭包与列表。在下面的例子中,我们首先定义一个简单的值列表。列表集合类型然后定义一个名为.each的函数。此函数将闭包作为参数,并将闭包应用于列表的每个元素

class Example {
   static void main(String[] args) {
      def lst = [11, 12, 13, 14];
      lst.each {println it}
   } 
}

当我们运行上面的程序,我们将得到以下结果 -

11 
12 
13 
14

使用映射闭包

以下示例显示了如何使用闭包。在下面的例子中,我们首先定义一个简单的关键值项Map。然后,映射集合类型定义一个名为.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}"}
   } 
}

当我们运行上面的程序,我们会得到以下结果 -

TopicName = Maps 
TopicDescription = Methods in Maps 
TopicName maps to: Maps 
TopicDescription maps to: Methods in Maps

通常,我们可能希望遍历集合的成员,并且仅当元素满足一些标准时应用一些逻辑。这很容易用闭包中的条件语句来处理。

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}
   } 
}

上面的例子显示了在闭包中使用的条件if(num%2 == 0)表达式,用于检查列表中的每个项目是否可被2整除。

当我们运行上面的程序,我们会得到以下结果 -

1 
2 
3 
4 
The list will only display those numbers which are divisible by 2.
2 
4 

闭包使用的方法

闭包本身提供了一些方法。

序号方法和描述
1find()

find方法查找集合中与某个条件匹配的第一个值。

2findAll()

它找到接收对象中与闭合条件匹配的所有值。

3any() & every()

方法any迭代集合的每个元素,检查布尔谓词是否对至少一个元素有效。

4collect()

该方法通过集合收集迭代,使用闭包作为变换器将每个元素转换为新值。


标签:Groovy

返回前面的内容

相关阅读 >>

Groovy 数据类型

Groovy 条件语句

Groovy 正则表达式

Groovy 泛型

Groovy 可选

Groovy 数字

Groovy 文件io

Groovy 构建器

Groovy jmx

Groovy 列表

更多相关阅读请进入《Groovy》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...