Given the following list with two monetary amounts of CHF 12.50 and CHF 99.35
we can easily calculate the grand total (sum up the monetary amounts) by using Java Streams. Note that
Money is backed by a
BigDecimal so precision is respected. For the sake of readability the code examples are working with
The result is a monetary amount
sum with CHF 111.85. Neat, isn't it?
But why MonetaryFunctions?
The example above uses
MonetaryFunctions::sum to sum up the monetary amounts. Of course you could simply use
MonetaryAmount::add as shown in the listing below.
MonetaryFunctions::sum you make sure, that only monetary amounts of the same currency are summed up. If you try to sum up CHF 5.50 and $ 12.33 using
MonetaryAmount::add, you then get