8

I want to sum the cost property of items in a List. I have written a stream to collect these items and perform the sum, using groupingBy(), as illustrated below.

groupingBy(
    ...,
    ...,
    Collectors.summingDouble(e->e.cost.doubleValue())
)

However, the cost field is a BigDecimal. In the code above, I am converting it to double, which makes me cringe. Is there a "drop-in" method I can write to that effect ? That would be an equivalent of summingBigDecimal(), which does not exist.

This is not a duplicate of Adding up BigDecimals using Streams as the answers are not applicable inside a groupingBy. Agreed with Anthony Garcia.

  • Maybe this works? `Collectors.reducing(BigDecimal.ZERO, BigDecimal::add)` – marstran Feb 20 '17 at 14:01
  • No it does not work. Thanks for offering. –  Feb 20 '17 at 14:24
  • 15
    This is not a duplicate of https://stackoverflow.com/questions/22635945/adding-up-bigdecimals-using-streams, as the answers are not applicable inside a `groupingBy`. The correct answer is to do `groupingBy(..., ..., Collectors.reducing(BigDecimal.ZERO, YourObjClass::cost, BigDecimal::add))`. – Anthony Garcia-Labiad Jul 03 '17 at 14:15

0 Answers0