本文介紹了java8流總和倍數(shù)的處理方法,對大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我很好奇,如何總結(jié)java8流中的多個(gè)變量.
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();
});
但是,這不會(huì)編譯,因?yàn)?lambda 表達(dá)式中的變量應(yīng)該是 final.
However, this does not compile as the variable in the lambda expression should be final.
推薦答案
假設(shè) slaContractList
是 SlaContract
對象的列表,它有構(gòu)造函數(shù) 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);
});
這篇關(guān)于java8流總和倍數(shù)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!