2016-03-03 142 views
-1

我一直在使用下面的函數來彙總數據相同:結果不再同時彙總數據

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(); 
    } 

所以它不再給我想要的結果。

+1

什麼是「預期結果」? – SomeDude

+0

@OldCurmudgeon我不使用equals()和hashCode() –

+0

@hamzaspecter - 你可能不會'但HashMap'會。無論如何,這是一個愚蠢的評論,因爲你的鑰匙是'字符串'。將刪除它。 – OldCurmudgeon

回答

1

在你的第一個片段中,你正在做一些添加currentaggregated。在你的第二個,你只參考aggregated所以可能不正確。

喜歡的東西:

 } 
     aggregated.setQuantity(aggregated.getQuantity() + current.getQuantity()); 
     aggregated.setSalary(aggregated.getSalary() + current.getSalary()); 

應該會更好。

+0

不,在我的第二個代碼中,它添加了所有字段的內容,除了我正在尋找具有相同性別和相同狀態的字段 –

+0

@hamzaspecter - 您的第二個片段**不會聚合**,它將「aggregate.quantity」和「aggregate.salary」保留爲「0」。你應該使用'+ current.getQuantity()'來說'+ aggregated.getQuantity()'。 – OldCurmudgeon

+0

我明白你的意思了,謝謝你的解釋 –