I have a list of objects List<WorkingActivityModel> mList = new ArrayList<>();
public class WorkingActivityModel {
private String name;
private Sales sales;
private Shifts shifts;
}
The Sales model is:
public class Sales {
private int product1;
private int product2;
}
The Shifts model is:
public class Shifts {
private int shift1;
private int shift2;
}
How can I group items in List<WorkingActivity> mList
by name and then sum corresponding sales and shifts? So if I have 2 items in the list with the same name then group them and sum its sales and shifts?
I have tried stream but with no success:
List<WorkingActivityModel> result = mList.stream()
.collect(groupingBy(WorkingActivityModel::getName, LinkedHashMap::new, toList()))
.values().stream()
.flatMap(Collection::stream)
.collect(toList());
Another option is:
List<WorkingActivity> mList = new ArrayList<>();
HashMap<String, List<WorkingActivityModel>> map = new HashMap<>();
for(WorkingActivityModel o : mList){
if (!map.containsKey(o.getKey())) {
List<WorkingActivityModel> list = new ArrayList<>();
list.add(o);
map.put(o.getKey(), list);
} else {
map.get(o.getKey()).add(o);
}
}
In this case, I don't know how to sum corresponding sales and Shifts
Edit
below an example of the expected result: