简体   繁体   中英

How to to collect the total sum of a specific object's attribute in a map of objects

I have a map of objects and I'm trying so get the sum of one of the attributes only, without doing it imperatively. This is the example

Class Project{
  String name
  Double budget
}
...
def projectsMap = Project.findAllByX...{...}

Now I've managed to count attributes but can't figure out how to sum the budget attribute only for all objects in the map. 3 days in with this, let's see if anybody here can help. Thx

This post was at the begging of my learning groovy. Maybe someone will look for this simple problem so I'll post my solution. By the way, the code in my question is not quite correct. Project.findAllByX(X) will not return a Map, it rather returns a List of the objects or null if none found.

def totalbudget = projectsList.sum{p -> p.budget}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM