lambda - 使用 Stream api 对多个变量进行减少和分配

标签 lambda java-8 java-stream

我需要在 lambda 中执行以下操作,但无法想到单流和减少可以提供帮助的方法:(

我有 Employee ArrayList,其中 name 成员变量可以在列表中的对象之间重复。我需要创建映射,其中键是员工姓名,值是对象,其中我们有该员工的 cost1 和 cost2 的总和

员工类有 -> 字符串名称、整数成本 1、整数成本 2

输出类有 -> 整数成本1、整数成本2

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

最佳答案

我假设你有一个类似这样的结构:

static class Output {
    private final int cost1;

    private final int cost2;

    public Output(int cost1, int cost2) {
        this.cost1 = cost1;
        this.cost2 = cost2;
    } 

    @Override
    public String toString() {
        return "cost1 = " + cost1 + " cost2 = " + cost2;
    }
    // ... getter
}  

static class Employee {
    private final String name;

    private final int cost1;

    private final int cost2;

    public Employee(String name, int cost1, int cost2) {
        this.name = name;
        this.cost1 = cost1;
        this.cost2 = cost2;
    }
 // ...getters      
}

那么解决方案是首先按 Employee::getName 分组,然后通过 Collectors.reducing 减少到 Output

  Map<String, Output> map = Arrays.asList(
                       new Employee("e", 12, 12), 
                       new Employee("f", 13, 13), 
                       new Employee("e", 11, 11))
            .stream()
            .collect(Collectors.groupingBy(Employee::getName,
                    Collectors.reducing(
                            new Output(0, 0),
                            emp -> new Output(emp.getCost1(), emp.getCost2()),
                            (left, right) -> new Output(left.getCost1() + right.getCost1(), left.getCost2() + right.getCost2()))));
    System.out.println(map); // {e=cost1 = 23 cost2 = 23, f=cost1 = 13 cost2 = 13}

关于lambda - 使用 Stream api 对多个变量进行减少和分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44437205/

相关文章:

C++ 将 Lambda 函数作为类构造函数参数传递

Lambda 架构 - 这个名字的由来是什么?

java - 并行流与流并行

Java Stream 关​​闭方法的不明确行为

java - 为什么 java 收集流对每个 getter 运行两次?

Java <Streams> 如何根据列表组件的数量对我的对象列表进行排序

java - 为什么我不能在 Java 8 lambda 表达式中引发异常?

python - 如何在 Python 中对集合运行操作并收集结果?

Java - 创建具有给定范围的 IntStream,然后使用映射函数随机化每个元素

java-8 - 在 java 8 中构建 Maven 程序集