John specter
John specter

Reputation: 171

grouping objects according to some fields

i have a List of an Object, with the following characteristics:

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

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

As input of the List, i have the following:

enter image description here

and as Output, i want to keep only one occurrence of the object with the same gender and the same state, in the same time sum the quantity and the salsary correspanding, like the following:

enter image description here

my question is how can i loop through myList, find objects with the same gender and the same state,keep only one occurence of them, and sum the quantity and the salary correspanding ??

in other words, for the first and second line (same gender, same state), keep only one line and sum the correspanding quantity and salary

Upvotes: 2

Views: 84

Answers (2)

Spotted
Spotted

Reputation: 4091

Equivalent with 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);
}

Upvotes: 0

lance-java
lance-java

Reputation: 27994

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

Upvotes: 4

Related Questions