简体   繁体   中英

Iterating through multiple loops and calculate total

I have to iterate through two arrays and calculate the salary total of the matching employee name.I have two arrays: empData:[Emp1,Emp2] and salData:[[name:Emp1,sal:1000],[name:Emp2,sal:5000],[name:Emp1,sal:6000],[name:Emp1,sal:7000]].I have to loop through empData and also salData and calculating the sum of the salary for the matching emp name and then push both the user name and the corresponding sal in to an array.

double total
empData.each{x ->
   sapData.each{ y ->
       if(y.name == x)
       {
          total =total + y.sal;
       }
  }

But getting an error Cannot cast object 'null1000.0' with class'java.lang.String' to class 'java.lang.Double'. If i declare total as string then the result is the cancatenation of sal.

You are not initializing total to anything. It is also possible that your salary values are actually strings; hard to tell from what you provided.

Initialize total to 0, and make sure to cast y.sal to double if necessary.

Ugh, loops and loops... have a look at the Groovy collection methods.

// poor emp3 has no salaryData
def employeeNames = ['emp1', 'emp2', 'emp3']
def salaryData = [[name: 'emp1', sal: 1000], [name: 'emp2', sal: 5000], [name: 'emp1', sal: 6000], [name:'emp1', sal: 7000]]
// here's our output array variable
def output = []
// for each employee
// find all the salaryData elements where salaryData.name == employeeName
// using that list, collect just the salary value
// using that list, sum it, adding to an initial value of 0
// append a new entry in output containing the name, and total salary 
employeeNames.each { employeeName ->
  output << [name: employeeName, totalSalary: salaryData.findAll { sal -> sal.name == employeeName }.collect { sal -> sal.sal }.sum(0)]
}
println output

groovyconsole yields: [[name:emp1, totalSalary:14000], [name:emp2, totalSalary:5000], [name:emp3, totalSalary:0]]

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