Starting with a list of objects containing two parameters notional and currency, how can I aggregate the total notional per currency?
Given:
case class T
Starting Scala 2.13
, most collections are provided with the groupMapReduce method which is (as its name suggests) an equivalent (more efficient) of a groupBy
followed by mapValues
and a reduce step:
trades.groupMapReduce(_.currency)(_.amount)(_ + _)
// immutable.Map[String,Int] = Map(JPY -> 10000100, USD -> 10010000, GBP -> 10001000)
This:
group
s elements based on their currency (group part of groupMapReduce)
map
s grouped values to their amount (map part of groupMapReduce)
reduce
s values (_ + _
) by summing them (reduce part of groupMapReduce).
This is an equivalent version performed in one pass through the List of:
trades.groupBy(_.currency).mapValues(_.map(_.amount).reduce(_+_))