Get the sum of list using Stream

Viewed 57

I have a list of LineItem.What i want is filter the list by the lineItemId and get the sum of quantity of the filtered element and filtered list both.

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

I wrote the code like this

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

Basically,What i want a Map,one key will contain the value of the filtered list and another will contain the sum of the quantity of the filtered list

1 Answers

It is not possible to store both data type List and Integer sum in a single map. But you can do something like below and while retrieving data from map you can typecast.

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);
Related