The inject method of list

The inject method of the list can be used for summing up the list contents.

def list = [1,2,3]
def sum = list.inject(0) { sum, item -> sum + item }
println sum

This will output

6

Another example would be summing only the even numbers in a list.

def list = [1,2,3,4,5,6]
def sum = list.inject(0) { sum, item -> sum + ( item % 2 == 0 ? item :0 ) }
println sum

This will output

12

.