java8流总和倍数

2022-01-09 00:00:00 sum collections java-8 java java-stream

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

I am curious, how to sum up multiple variables in a java8 stream.

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 表达式中的变量应该是 final.

However, this does not compile as the variable in the lambda expression should be final.

推荐答案

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

Assuming slaContractList is a list of SlaContract objects, and it has constructor SlaContract(numberOfCPUs, networkBandwith, memory) you can:

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

相同的解决方案,但对于简单的类:

The same solution, but for simple class:

Point sumPoint = pointsList.stream()
    .reduce(new Point(0, 0), (p1, p2) -> {
         return new Point(p1.x + p2.x, p1.y + p2.y);
    });

相关文章