Groovy provides findINdexOf method that return the index
of first element that matches to given criteria.
public int
findIndexOf(Closure condition)
Iterates over the elements of an Iterable and returns the
index of the first item that satisfies the condition specified by the closure,
if no element matches, it return -1.
public int
findIndexOf(int startIndex, Closure condition)
Iterates over the elements of an Iterable, starting from
a specified startIndex, and returns the index of the first item that satisfies
the condition specified by the closure, if no element matches, it return -1.
HelloWorld.groovy
numbers = [2, 5, 8, 1, 32, 49, 65, 43, 70, 21, 42] def index1 = numbers.findIndexOf{ it % 7 == 0} def index2 = numbers.findIndexOf{ it % 11 == 0} println "Element index that divisible by 7 $index1" println "Element index that divisible by 11 $index2"
Output
Element index that divisible by 7 5
Element index that divisible by 11 -1
Bardzo ciekawy artykuł. Pozdrawiam serdecznie !
ReplyDelete