我正在嘗試對 List 的欄位求和并回傳值。我想為此使用流,但我是流的新手,不確定流是否可以完成此操作。這是我嘗試過的,但我認為語法不正確。
public double calculateCartTotal(ArrayList cartItems) {
this.totalPrice = cartItems.stream()
.map(item -> item.getTotalItemPrice())
.reduce(0, (a, b) -> a b);
return totalPrice;
}
背景關系的相關類結構。
public class Cart {
private double totalPrice;
private List<CartItem> cartItems;
public Cart() {
super();
this.totalPrice = 0;
this.cartItems = new ArrayList<CartItem>();
}
//other methods
}
public class CartItem {
private Product productName;
private int numberOfUnits;
private double totalItemPrice;
private double unitPrice;
public CartItem(Product productName, int numberOfUnits) {
super();
this.productName = productName;
this.numberOfUnits = numberOfUnits;
}
//other methods
}
獲取總價和單價方法
public double getTotalItemPrice() {
return this.getUnitPrice() * numberOfUnits;
}
public double getUnitPrice() {
return Double.parseDouble(productName.getCurrentPrice());
}
uj5u.com熱心網友回復:
您需要將cartItems引數宣告為List<CartItem>:
public double calculateCartTotal(List<CartItem> cartItems) {
this.totalPrice = cartItems.stream()
.mapToDouble(CartItem::getTotalItemPrice)
.sum();
return totalPrice;
}
uj5u.com熱心網友回復:
您的代碼有兩個問題。
缺少 的型別引數
ArrayList。這是有問題的,因為現在我們不知道串列是否真的包含CartItems。此外,您通常希望避免使用集合的實作來進行宣告,例如List<CartItem> items = new ArrayList<>();更好。不將流轉換為
DoubleStrem. 使用 aDoubleStream的優點是它不會將原始 double 轉換為Double物件。此外,它與普通的數字不同,Stream因此它帶有有用的方法,例如sum我們不必使用reduce.
示例代碼
public double calculateCartTotal(List<CartItem> cartItems) {
this.totalPrice = cartItems.stream()
.mapToDouble(i -> i.getTotalItemPrice())
.sum();
return totalPrice;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/339435.html
