簡體   English   中英

使用 Stream 對 List 中的 Object 字段求和

[英]Using Stream to sum Object feilds in List

我正在嘗試對 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());
    }

您需要將cartItems參數聲明為List<CartItem>

public double calculateCartTotal(List<CartItem> cartItems) {

    this.totalPrice = cartItems.stream()
           .mapToDouble(CartItem::getTotalItemPrice)
           .sum();
    return totalPrice;

}

您的代碼有兩個問題。

  1. 缺少ArrayList類型參數。 這是有問題的,因為現在我們不知道列表是否真的包含CartItem s。 此外,您通常希望避免使用集合的實現進行聲明,例如List<CartItem> items = new ArrayList<>(); 好多了。

  2. 不將流轉換為DoubleStrem 使用DoubleStream的優點是它不會將原始 double 轉換為Double對象。 此外,與普通的Stream不同,它可以使用 number ,因此它帶有像sum這樣的有用方法,我們不必使用reduce

示例代碼

public double calculateCartTotal(List<CartItem> cartItems) {
    this.totalPrice = cartItems.stream()
        .mapToDouble(i -> i.getTotalItemPrice())
        .sum();
    return totalPrice;  
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM