我有一个对象列表,具有以下特征:
Class myObject{
String gender;
String state;
int quantity;
int Salary;
}
List<myObject> myList=new ArrayList<Object>;
作为列表的输入,我有以下内容:
作为输出,我想只保留一次具有相同性别和相同状态的对象,同时求和相应的数量和工资,如下所示:
我的问题是如何循环遍历myList,找到具有相同性别和相同状态的对象,只保留它们出现一次,并将数量和相应的工资求和?
也就是说,对于第一行和第二行(相同性别,相同州),只保留一行,并将对应的数量和工资相加
最佳答案
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();
}
关于java - 根据某些字段对对象进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35769189/