我一直在使用下面的函數來彙總數據相同:結果不再同時彙總數據
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的結構:
public class MyObject {
private String gender;
private String state;
private int quantity;
private int Salary;
//getters & setters}
而是因爲我不得不宣佈MyObject來爲屬性私人,我把它改爲:
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();
}
所以它不再給我想要的結果。
什麼是「預期結果」? – SomeDude
@OldCurmudgeon我不使用equals()和hashCode() –
@hamzaspecter - 你可能不會'但HashMap'會。無論如何,這是一個愚蠢的評論,因爲你的鑰匙是'字符串'。將刪除它。 – OldCurmudgeon