Java Reference
In-Depth Information
Figure B.1. Access any linear collection using an index from either end. The first element is at index 0. The last
element is at index -1. You can also use subranges, as in mylist[-4..-2].
Array-like Access
Linear collections support element access through an index from either end, or even using
a range.
Groovy adds methods like
pop
,
intersect
, and
reverse
to collections. See the
GroovyDocs for details.
There are two ways to apply a function to each element. The
spread-dot
operator (
.*
)
makes it easy to access a property or apply a method to each element:
assert cities*.size() == [8, 6, 9, 7]
The
collect
method takes a closure as an argument and applies it to each element of the
collection, returning a list with the results. This is similar to the spread-dot operator, but
can do more general operations:
def abbrev = cities.
collect
{ city -> city[0..2].toLowerCase() }
assert abbrev == ['new', 'bos', 'cle', 'sea']
The word
city
here used before the arrow is like a dummy argument for a method call.
The closure extracts the first three letters of each element of the list and then converts them
to lowercase.