Thursday 24 January 2019

Groovy: List: sum(): Return sum of all the elements in the list


Groovy provides sum() method, it return the sum of all the elements in a list. It internally uses ‘+’ operator to perform the sum.

‘sum’ method is available in below overloaded forms.

public Object sum()
public Object sum(Object initialValue)
public Object sum(Closure closure)
public Object sum(Object initialValue, Closure closure)

HelloWorld.groovy
numbers = [0, 1, 2, 3, 4, 5]

def sumOfElements = numbers.sum()

println "sumOfElements : ${sumOfElements}"

Output
sumOfElements : 15

You can even provide initial value while calculating the sum.


HelloWorld.groovy
numbers = [0, 1, 2, 3, 4, 5]

def sumOfElements = numbers.sum(100)

println "sumOfElements : ${sumOfElements}"

Output
sumOfElements : 115

You can even provide a closure the sum method.


HelloWorld.groovy

numbers = [0, 1, 2, 3, 4, 5]

def sumOfElements = numbers.sum()
def sumOfSquaresOfElements = numbers.sum {it * it}

println "sumOfElements : ${sumOfElements}"
println "sumOfSquaresOfElements : ${sumOfSquaresOfElements}"

Output
sumOfElements : 15
sumOfSquaresOfElements : 55




Previous                                                 Next                                                 Home

No comments:

Post a Comment