我很好奇,如何总结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.
假设 slaContractList
是 SlaContract
对象的列表,它有构造函数 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);
});
这篇关于java8流总和倍数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!