java实现球队分组,用Java将列表中的项目分组

I have a list of objects List 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 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 result = mList.stream()

.collect(groupingBy(WorkingActivityModel::getName, LinkedHashMap::new, toList()))

.values().stream()

.flatMap(Collection::stream)

.collect(toList());

Another option is:

List mList = new ArrayList<>();

HashMap> map = new HashMap<>();

for(WorkingActivityModel o : mList){

if (!map.containsKey(o.getKey())) {

List 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:

XLtad.png

解决方案

You can do that using a custom merge operation defined such that performing toMap becomes slightly easier.

Collection result = mList.stream()

.collect(Collectors.toMap(WorkingActivityModel::getName, Function.identity(),

(a, b) -> WorkingActivityModel.mergeModels(a, b))) // WorkingActivityModel::mergeModels

.values();

The mergeModels is a static method that I have defined within WorkingActivityModel class such as it deals with the logic of merging two similarly named models.

static WorkingActivityModel mergeModels(WorkingActivityModel model1, WorkingActivityModel model2) {

return new WorkingActivityModel(model1.name,

Sales.mergeSales(model1.sales, model2.sales),

Shifts.mergeShifts(model1.shifts, model2.shifts));

}

Of course, the mergeSales and mergeShifts follow the same pattern and are trivial to implement.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值