Wednesday 23 January 2019

Groovy: List: find(): Find first element that matches given criteria


Groovy Collection provides find method, that returns the first element that matches to given criteria.

public Object find(Closure closure)
Return the first Object found in the collection that matches to given closure, in the order of the collections iterator, or null if no element matches

HelloWorld.groovy

numbers = [2, 5, 8, 1, 32, 49, 65, 43, 70, 21, 42]

def number = numbers.find { it % 7 == 0}

println "First number in the list $numbers that is divisible by 7 is : $number"

Output
First number in the list [2, 5, 8, 1, 32, 49, 65, 43, 70, 21, 42] that is divisible by 7 is : 49


Previous                                                 Next                                                 Home

No comments:

Post a Comment