July 2013
Intermediate to advanced
370 pages
8h 27m
English
We know how to iterate over a collection and perform operations on each element. However, if
we want to search for a particular element,
each
or
collect
is not convenient. Instead, we should use
find
, like so:
| WorkingWithCollections/Find.groovy | |
| | lst = [4, 3, 1, 2, 4, 1, 8, 9, 2, 6] |
| | |
| | println lst.find { it == 2 } |
The code picks up the first element, which equals 2, as we see from the output:
| | 2 |
In this code, we’re looking for an object that matches value 2 in the collection.
find
gets the
first occurrence of the matching object. In this case, it returns the object at position 3.
Just like the
each
method, the
find
method
iterates over
the collection, but only until the closure returns a true. On ...
Read now
Unlock full access