0

I have a methode that use an effectively final variable total intialised with 0, i'm suposed to have the sum of products price but i'm always getting 0, can someone tell me what i'm missing

    public BigDecimal getTotalAmount() {
        BigDecimal total = BigDecimal.ZERO;
        products.forEach(product -> total.add(product.getPrice()));
        return total;
    }
DEV
  • 1,607
  • 6
  • 19
  • 3
    BigDecimal is *immutable* type. When you do `total.add(product.getPrice())` it doesn't *modify* object held by `total`, but produces new BigDecimal object which you discard. – Pshemo Aug 19 '23 at 18:57
  • 1
    I'm pretty sure that `BigDecimal.add` returns a new BigDecimal and doesn't mutate the original variable. Try using `reduce` in place of `forEach` – Christian Vincenzo Traina Aug 19 '23 at 18:58
  • 3
    Related: [Adding up BigDecimals using Streams](https://stackoverflow.com/q/22635945) – Pshemo Aug 19 '23 at 18:59
  • thanks that's answering my question – DEV Aug 19 '23 at 19:00

0 Answers0