我一直在使用以下功能来汇总数据:
private Collection<MyObject> aggregate(List<MyObject> objects) {
Map<String, MyObject> map = new HashMap<String, MyObject>();
for (MyObject current : objects) {
String key = String.format("%s:%s", current.gender, current.state);
MyObject aggregated = map.get(key);
if (aggregated == null) {
aggregated = new MyObject();
aggregated.gender = current.gender;
aggregated.state = current.state;
map.put(key, aggregated);
}
aggregated.quantity += current.quantity;
aggregated.salary += current.salary;
}
return map.values();
}
MyObject Structure:
public class MyObject {
private String gender;
private String state;
private int quantity;
private int Salary;
//getters & setters}
但是因为我必须将MyObject属性声明为Private,我将其更改为以下内容:
private static Collection<MyObject> aggregate(List<MyObject> objects) {
Map<String, MyObject> map = new HashMap<String, MyObject>();
for (MyObject current : objects) {
String key = String.format("%s:%s", current.gender, current.state);
MyObject aggregated = map.get(key);
if (aggregated == null) {
aggregated = new MyObject();
aggregated.setGender(current.getGender());
aggregated.setState(current.state);
map.put(key, aggregated);
}
int quantity=0,salary=0;
quantity=quantity+aggregated.getQuantity();
salary= salary+aggregated.getSalary();
aggregated.setQuantity(quantity);
aggregated.setSalary(salary);
}
return map.values();
}
所以它不再给我想要的结果。
答案 0 :(得分:1)
在您的第一个片段中,您正在执行将current
添加到aggregated
的操作。在你的第二个你只引用aggregated
,所以可能不对。
类似的东西:
}
aggregated.setQuantity(aggregated.getQuantity() + current.getQuantity());
aggregated.setSalary(aggregated.getSalary() + current.getSalary());
应该会更好。