【发布时间】:2017-11-10 06:09:13
【问题描述】:
我需要在 lambda 中执行以下操作,但无法想到单流和减少可以提供帮助的方式:(
我有 Employee ArrayList,其中 name 成员变量可以在列表中的对象之间重复。我需要创建地图,其中键是员工姓名,值是对象,我们有该员工的 cost1 和 cost2 sum。
员工类有 -> 字符串名称、整数 cost1、整数 cost2
输出类有 -> Integer cost1, Integer cost2
List <Employee> employeeList = new ArrayList<>();
// data population in inputMap
Map<String, Output> outputMap = new HashMap<>();
for (Employee emp : employeeList)
{
Output op = outputMap.get(emp.getName());
if(op == null){
Output newOp = new Output ();
newOp.setCost1(emp.getCost1())
newOp.setCost2(emp.getCost2())
newOp.put(emp.getName(), newOp);
}else{
int cost1 = op.getCost1() + emp.getCost1();
int cost2 = op.getCost2() + emp.getCost2();
op.setCost1(cost1);
op.setCost2(cost2);
newOp.put(emp.getName(), op);
}
}
【问题讨论】:
-
我不明白你想做什么,你能再具体点吗?
-
@Eugene :是的,我可以使用。但是如果可能的解决方案使用 java 自己的类将更有助于理解它是否可以在单个流中完成
-
@SamedSivaslıoğlu:对于每个员工姓名,将 cost1 和 cost2 相加并放入地图。
标签: lambda java-8 java-stream