Adding up BigDecimals using Streams
Quick and dirty solution to sum BigDecimal
values using streams applies the reduce()
method:
Here bigDecimals
signifies your collection of BigDecimal
; stream()
transforms it into a stream; and reduce()
consolidates it all beginning from BigDecimal.ZERO
, leveraging BigDecimal::add
method to accumulate the total sum.
Operational scenarios
Ever found yourself working with complex objects and pulling hairs over calculations? Fear not, Java provides a simple way using the map
function combined with reduce
. For example, you have a list of invoices and you want to calculate the total of all invoices:
This piece of code applies the Invoice::total
method on each invoice, converts it into the relevant amount, and then adds it all up to produce the grand total. But beware! Life is full of surprises like nulls that you might encounter along the way. Dismiss this headache using filter(Objects::nonNull)
:
This code works to filter out the nulls before the rest of the stream operations are applied, thus preventing any unwanted **NullPointerException
**s.
Ensuring precision
Creative code requires statistical data to ensure its efficiency, Eclipse Collections comes to the rescue providing summarizingBigDecimal()
for your needs:
Here, MutableBigDecimalSummaryStatistics
is like the Swiss army knife of statistical data, providing you with the sum, average, count, min, and max. And always remember, when performing BigDecimal
calculations, use the adapted methods and avoid converting to double
or float
to safeguard precision.
Cauldron of Customizations
When dealing with BigDecimal
values, customization is crucial for precision, performance, and catering to your specific needs. In such cases, a custom Collector
magically solves our problem:
This custom Collector
, named summingUp
, is designed to focus on maintaining precision during the accumulation process.
Check for hidden traps
Steering clear of calculations errors and nulls is as important as finding buried treasure! Here's how to safeguard your calculations:
This safeInvoiceTotal
map function wards off the Dementors, ensuring no null values slip in your calculation pipeline.
Was this article helpful?