"Groovy"-Loop (study notes) @20210222

Use each method

listFoo.each { item ->
	// do some stuff
}

Use find method

Can you break from a Groovy “each” closure?

When using find to traverse, returning true in Cloure will stop the traversal:

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

You can also implement your own find function through metaprogramming:

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
}

Guess you like

Origin blog.csdn.net/u013670453/article/details/113928710
Recommended