MyObject structure is:
public class MyObject {
String gender;
String state;
int quantity;
int Salary;}
我有以下功能。它允许我在性别和对象的状态维度中聚合数据:
private static Collection<MyObject> aggregate(List<MyObject> objects) {
int nombre=0;
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);
}
if(current.getSalary()!=0)
nombre+=1;
aggregated.setQuantity(aggregated.getQuantity() + current.getQuantity());
aggregated.setSalary((aggregated.getSalary() + current.getSalary())/nombre);
}
return map.values();
}
我希望获得汇总数据的平均工资。 &#34; nombre&#34;出了点问题。属性。
实际上它给了我以下结果:
element : 1 M 40 1200
element : 1 F 35 2000
element : 1 M 20 200
element : 1 M 80 300
element : 1 F 35 2000
聚会后的内容:
`element : 1 M 140 333
element : 1 F 70 2000`
但我期待:
聚合后的内容:
element : 1 M 140 566
element : 1 F 70 2000
答案 0 :(得分:2)
我在这里至少看到四个问题:
nombre
是int
,假设getSalary()
也会返回int
,因为当所有操作数都是整数时,因为1/2 = 0,所以会出现截断/舍入问题。 nombre
)。您希望每个聚合都有一个计数器。答案 1 :(得分:0)
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);
}
aggregated.nombre+=1;
aggregated.setQuantity(aggregated.getQuantity() + current.getQuantity());
aggregated.setSalary((aggregated.getSalary() + current.getSalary()));
}
for(MyObject c : map.values()){
c.setSalary(c.getSalary()/c.nombre);
}
return map.values();
}
我在MyObject中添加了一个属性nombre。