Java Money - Sum up monetary amounts
Java Money (JSR-354) provides an excellent API (and SPI) to deal with money in Java. The following example shows how easily it can be used with Java Streams to sum up MonetaryAmounts
.
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 double
values.
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.
By using 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 MonetaryException
.