Java Money - Sum up monetary amounts
![Java Money - Sum up monetary amounts](/content/images/size/w960/2023/02/schweizisk-franc.webp)
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
![](https://wangler.io/content/images/2023/02/List-Of-Monetary-Amounts.jpeg)
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.
![](https://wangler.io/content/images/2023/02/Sum-it-up-1.jpeg)
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.
![](https://wangler.io/content/images/2023/02/Sum-by-add.jpeg)
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
.