使用 each 方法
listFoo.each { item -> // do some stuff }
使用 find 方法
Can you break from a Groovy “each” closure?
当使用 find 遍历时,在 Cloure 中返回 true 将停止遍历:
def a = [1, 2, 3, 4, 5, 6, 7] a.find { if (it > 5) return true // break println it // do the stuff that you wanted to before break return false // keep looping } // 该程序将输出 1, 2, 3, 4, 5
也可以通过元编程实现自己的 find 函数:
List.metaClass.eachUntilGreaterThanFive = { closure -> for ( value in delegate ) { if ( value > 5 ) break closure(value) } } def a = [1, 2, 3, 4, 5, 6, 7] a.eachUntilGreaterThanFive { println it }