根据某些字段对对象进行分组

时间:2016-03-03 10:14:44

标签: java arraylist

我有一个对象列表,具有以下特征:

Class myObject{
  String gender;
  String state;
  int quantity;
  int Salary;
}

List<myObject> myList=new ArrayList<Object>;

作为List的输入,我有以下内容:

enter image description here

并且作为输出,我想只保留具有相同性别和相同状态的对象的一次出现,同时总结数量和salsary correspanding,如下所示:

enter image description here

我的问题是我如何循环浏览myList,查找具有相同性别和相同状态的对象,只保留一次,并将数量与工资相加?

换句话说,对于第一行和第二行(同性别,相同的州),只保留一行并将相应的数量和工资相加

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

与Java 8等效:

private static Collection<myObject> aggregate(List<myObject> objects) {
        return objects.stream()
                .collect(groupingBy(myObject::genderAndState, reducing(new myObject(), myObject::merge)))
                .values();
    }

private static myObject merge(myObject o1, myObject o2) {
    myObject tmp = new myObject();
    tmp.gender = o2.gender;
    tmp.state =  o2.state;
    tmp.quantity= o1.quantity + o2.quantity;
    tmp.salary = o1.salary + o2.salary;
    return tmp;
}

private static String genderAndState(myObject o) {
    return o.gender.concat(o.state);
}