Computing the Sum of Items in a Collection

To determine the sum of items in a collection call its sum() function with no arguments. This works for any items that support a plus operator.

For example, you can sum a list of numbers like this to produce the result 1259.13:

def salaries = [123.45, 678.90, 456.78]
// Compute the sum of the list of salaries
def total = salaries.sum()
However, since strings also support a plus operator, it might surprise you that the following also works to produce the result VincentvanGogh:
def names = ['Vincent','van','Gogh']
def sumOfNames = names.sum()
If you need to find the sum of a subset of items in a collection based on a particular condition, then first call findAll() to identify the subset you want to consider, then collect() the value you want to sum, then finally call sum() on that collection. For example, to find the sum of all accesses for all users with over 100 accesses, do the following to compute the total of 2154:
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]
            ]
// Compute sum of all user accesses for users having more than 100 accesses
def total = users.findAll{ it.value.accesses > 100 }
                 .collect{ it.value.accesses }
                 .sum()