Aggregate list values in Scala

前端 未结 3 2013
孤街浪徒
孤街浪徒 2021-02-02 18:08

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         


        
3条回答
  •  时光说笑
    2021-02-02 18:54

    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:

    • groups elements based on their currency (group part of groupMapReduce)

    • maps grouped values to their amount (map part of groupMapReduce)

    • reduces 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(_+_))
    

提交回复
热议问题