Starting with a list of objects containing two parameters notional and currency, how can I aggregate the total notional per currency?
Given:
case class Trade(name: String, amount: Int, currency: String)
val trades = List(
Trade("T150310", 10000000, "GBP"),
Trade("T150311", 10000000, "JPY"),
Trade("T150312", 10000000, "USD"),
Trade("T150313", 100, "JPY"),
Trade("T150314", 1000, "GBP"),
Trade("T150315", 10000, "USD")
)
How can I get:
Map(JPY -> 10000100, USD -> 10010000, GBP -> 10001000)
I wrote a simple group-by operation (actually a
Groupabletraitwith an implicit conversion from anIterable) which would allow you to group your trades by theircurrency:So
Groupableis simply providing a way to extract a key from each item in anIterableand then grouping all such items which have the same key. So, in your case:You can now do a quite simple
mapElements(mmis aMap) and afoldLeft(or/:– well worth understanding thefoldLeftoperator as it enables extremely concise aggregations over collections) to get the sum:Apologies if I’ve made some mistakes in that last line.
tsare the values ofmm, which are (of course)Iterable[Trade].