简体   繁体   中英

Sum Bigdecimals inside Stream

I´m using Java 8 Stream where I iterate over two collections, and after pass a filter I want to sum one of the bigdecimal variables that I have inside my stream to an external bigDecimal variable "restrictionsNumber"

Here my code:

     final BigDecimal restrictionsNumber = cmd.amount.getNumberOfUnits();
        order.products()
             .stream()
             .flatMap(product -> product.getRestrictions()
                                    .stream()
                                    .filter(restriction -> restriction.equals(newProductRestriction))
                                    .map(restriction -> restrictionsNumber.add(product.getAmount()
                                                                            .getNumberOfUnits())));

The last map is the one where I´m trying to sum the two bigdecimals. I know I´m doing something wrong. Can anyone give me an advise about how to do it with Stream.

I´m trying to refactor from this old fashion code

 final BigDecimal restrictionsNumber = cmd.amount.getNumberOfUnits();
 for (Product product : order.products()) {
     for (String oldProductRestriction : product.getRestrictions()) {
         if (oldProductRestriction.equals(newProductRestriction)) {
            restrictionsNumber = restrictionsNumber.add(product.getAmount()
                                                                       .getNumberOfUnits());
          }
      }
  }

Regards.

This may be what you need (but it keeps adding the same amount several times for each product, in line with your original code, which seems weird):

BigDecimal sum = order.products()
     .stream()
     .flatMap(product -> product.getRestrictions()
                  .stream()
                  .filter(restriction -> restriction.equals(newProductRestriction))
                  .map(restriction -> product.getAmount().getNumberOfUnits()))
     .reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal result = restrictionsNumber.add(sum);

It sounds like you want to use the " reduce " operation. Reduce is used for operations like summing over a whole stream, or adding finding the maximum.

(If you want your addition to happen for a single stream element then your question was unclear to me, please add detail)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM