Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Groovy, how do I add up the values for a certain property in a map?

Tags:

groovy

I have the following map:

def map = [];
map.add([ item: "Shampoo", count: 5 ])
map.add([ item: "Soap", count: 3 ])

I would like to get the sum of all the count properties in the map. In C# using LINQ, it would be something like:

map.Sum(x => x.count)

How do I do the same in Groovy?

like image 553
Daniel T. Avatar asked Aug 14 '12 04:08

Daniel T.


3 Answers

You want to use the collect operator. I checked the following code with groovysh:

list1 = []
total = 0
list1[0] = [item: "foo", count: 5]
list1[1] = [item: "bar", count: 3]
list1.collect{ total += it.count }
println "total = ${total}"
like image 100
nickdos Avatar answered Nov 17 '22 15:11

nickdos


Assuming you have a list like so:

List list = [ [item: "foo", count: 5],
              [item: "bar", count: 3] ]

Then there are multiple ways of doing it. The most readable is probably

int a = list.count.sum()

Or you could use the Closure form of sum on the whole list

int b = list.sum { it.count }

Or you could even use a more complex route such as inject

int c = list.count.inject { tot, ele -> tot + ele } // Groovy 2.0
//  c = list.count.inject( 0 ) { tot, ele -> tot + ele } // Groovy < 2.0

All of these give the same result.

assert ( a == b ) && ( b == c ) && ( c == 8 )

I would use the first one.

like image 40
tim_yates Avatar answered Nov 17 '22 14:11

tim_yates


First of all, you're confusing map and list syntax in your example. Anyhow, Groovy injects a .sum(closure) method to all collections.

Example:

[[a:1,b:2], [a:5,b:4]].sum { it.a }
===> 6
like image 1
Lauri Piispanen Avatar answered Nov 17 '22 15:11

Lauri Piispanen