Computing the Maximum Item in a Collection
To determine the maximum item in a collection call its max() function with no arguments.
However, if you need to find the maximum from a subset of items in a collection based on
a particular condition, then pass a closure to max()
that identifies
the expression for which to find the maximum value. For example, to find the maximum
item in the following list of users based on the number of accesses they've made to a
system, do the following:
def users = [
'smuench':[name:'Steve', badge:'A123', accesses: 1001],
'sburns':[name:'Steve', badge:'C789', accesses: 52],
'qbronson':[name:'Quello', badge:'Z231', accesses: 152],
'jevans':[name:'Joe', badge:'B456', accesses: 1001]
]
// Return the map entry with the maximum value based on accesses
def maxUser = users.max { it.value.accesses }
max()
function returns the first item having the maximum
accesses
value of 1001, which is the map entry corresponding to
smuench
. However, to return all users having the maximum value
requires first determining the maximum value of accesses and then finding all map
entries having that value for their accesses
property. This code looks
like:// Find the maximum value of the accesses property
def maxAccesses = users.max { it.value.accesses }.value.accesses
// Return all map entries having that value for accesses
def usersWithMaxAccesses = users.findAll{ it.value.accesses == maxAccesses }
There is often more than one way to solve a problem. Another way to compute the maximum
number of accesses would be to first collect()
all the
accesses
values, then call max()
on that
collection of numbers. That alternative approach looks like this:
// Find the maximum value of the accesses property
def maxAccesses = users.collect{ it.value.accesses }.max()
[
smuench:[name:Steve, badge:A123, accesses:1001],
jevans:[name:Joe, badge:B456, accesses:1001]
]
If the collection whose maximum element you seek requires a custom comparison to be done
correctly, then you can pass the same kind of two-parameter comparator closure that the
sort()
function supports.