簡體   English   中英

使用 Stream 獲取列表的總和

[英]Get the sum of list using Stream

我有一個 LineItem 列表。我想要的是通過 lineItemId 過濾列表並獲取過濾元素和過濾列表的數量之和。

public class LineItem {
private Item item;
private int quantity;
private String lineItemId;
}

我寫了這樣的代碼

purchases.stream()
            .map(purchaseItem -> identifyAndGetLineItem(purchaseItem,awardPointsForSaleRequest.getLineItems()))
            .filter(lineItem -> lineItem.getQuantity() > 0)
            .collect(Collectors.toMap())

基本上,我想要一個 Map,一個鍵將包含過濾列表的值,另一個將包含過濾列表數量的總和

不可能將數據類型 List 和 Integer 和存儲在單個 map 中。 但是您可以執行以下操作,並且在從 map 檢索數據時,您可以進行類型轉換。

List<LineItem> lineItemList = lineItems.stream()
                                       .filter(lineItem -> lineItem.getLineItemId() == "filter data")
                                       .collect(Collectors.toList());
Integer sum = lineItemList.stream().map(LineItem::getQuantity).reduce(0, Integer::sum);
Map<String, Object> list = Map.of("list", lineItemList, "sum", sum);

暫無
暫無

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

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