我很好奇,如何总结一个java8流中的多个变量。

Integer wCPU = 0;
Double wnetwork = 0.0;
Double wMem = 0.0;

this.slaContractList.forEach(sla -> {
    wCPU += sla.getNumberOfCPUs();
    wnetwork += sla.getNetworkBandwith();
    wMem += sla.getMemory();
});

但是,这不能编译,因为lambda表达式中的变量应该是最终的。

最佳答案

假设slaContractListSlaContract对象的列表,并且它具有构造函数SlaContract(numberOfCPUs, networkBandwith, memory),则您可以:

SlaContract sumContract = slaContractList.stream()
    .reduce(new SlaContract(0, 0.0, 0.0), (sla1, sla2) -> {
         return new SlaContract(sla1.getNumberOfCPUs() + sla2.getNumberOfCPUs(), sla1.getworkBandwith() + sla2.getworkBandwith(), sla1.getMemory() + sla2.getMemory());
    });

Double wnetwork = sumContract.getworkBandwith();
Double wMem = sumContract.getMemory();
Integer wCPU = sumContract.getNumberOfCPUs();

相同的解决方案,但对于简单的类:
Point sumPoint = pointsList.stream()
    .reduce(new Point(0, 0), (p1, p2) -> {
         return new Point(p1.x + p2.x, p1.y + p2.y);
    });

关于java8流总和倍数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40567935/

10-09 01:14