加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

GDK对Object对象的扩展

发布时间:2020-12-14 16:48:26 所属栏目:大数据 来源:网络整理
导读:GDK对Object对象的扩展 Groovy添加了若干方法到 java.lang.Object 当中,其中大部分处理类型作为集合或聚合,如列表或DOM节点。 Return Value Method Description Boolean any {closure} returns true if the closure returns true for any item List collec

GDK对Object对象的扩展

Groovy添加了若干方法到java.lang.Object当中,其中大部分处理类型作为集合或聚合,如列表或DOM节点。

Return Value

Method

Description

Boolean

any {closure}

returns true if the closure returns true for any item

List

collect {closure}

returns a list of all items that were returned from the closure

Collection

collect(Collection collection) {closure}

same as above,but adds each item to the given collection

void

each {closure}

simply executes the closure for each item

void

eachWithIndex {closure}

same as each{} except it passes two arguments: the item and the index

Boolean

every {closure}

returns true if the closure returns true for all items

Object

find {closure}

returns the first item that matches the closure expression

List

findAll {closure}

returns all items that match the closure expression

Integer

findIndexOf {closure}

returns the index of the first item that matched the given expression

**注释**以上表格只列出部分常用的方法,添加到`java.lang.Object`中的完整方法列表请参阅[GDK documentation on Object ](http://groovy.codehaus.org/groovy-jdk/java/lang/Object.html) 在Groovy当中,自从`return`关键字变成可选之后,闭包在这种情况下被当做`判断`,并且在闭包当中你无论给出的是什么表达式,返回的结果都是布尔型的。这种`判断`允许你以一种非常简洁的方式在集合对象上执行操作。 ### 例子
def numbers = [ 5,7,9,12 ]
assert numbers.any { it % 2 == 0 }                        //returns true since 12 is even

assert numbers.every { it > 4 } //returns true since all #s are > 4

assert numbers.findAll { it in 6..10 } == [7,9] //returns all #s > 5 and < 11

assert numbers.collect { ++it } == [6,8,10,13] //returns a new list with each # incremented

numbers.eachWithIndex{ num,idx -> println "$idx: $num" } //prints each index and number

原文地址 http://groovy.codehaus.org/GDK+Extensions+to+Object

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读