2015-07-12 54 views
4

經過數小時的無望搜索,我決定創建一個問題。 我真的沒有找到任何東西,我可以如何將這種老式的編碼方式轉換爲流/ lambda。Java8:將舊的ForEach方法「翻譯」爲Lambda/Stream

也許有人可以向我解釋。謝謝。

public double getSum() { 
    double sum = 0; 
    for (Product product : productList) { 
     sum += product.getPrice(); 
    } 
    return sum; 
} 
+4

順便說一句,這是最好不要使用雙浮法代表貨幣。請參閱http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency – dnault

回答

3

您可以使用以下方法:

double sum = productList.stream().mapToDouble(product -> product.getPrice()).sum(); 
+2

或者,使用方法引用而不是lambda表達式:mapToDouble(Product :: getPrice) – dnault

+0

非常感謝=)。 – Stackman

+1

請注意,與OP代碼相比,您可能會得到稍微不同的結果,因爲流版本實現的Kahan總和可抵抗錯誤積累。 –