Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of Array List In groovy

Tags:

groovy

I have an Array List in groovy in below format. I want the sum of integer values in this list.

[ {"value":1}, {"value":1}, {"value":10}, {"value":11}, {"value":12}]

Expected Output

1+1+10+11+12=35 
like image 471
JavaAppUser Avatar asked Dec 28 '16 08:12

JavaAppUser


2 Answers

Oh it's very easy.

list.value.sum()
like image 161
JavaAppUser Avatar answered Oct 19 '22 23:10

JavaAppUser


I would prefer using the Groovy Spread Operator.

The Spread Operator (*.) is used to invoke an action on all items of an aggregate object.

Specific to your question, the best way coding the desired result is:

list*.value.sum()

The difference is only a * but it is best practice to use the language correctly.

like image 8
Rotem Avatar answered Oct 19 '22 21:10

Rotem