Aggregate list values in Scala

前端 未结 3 2017
孤街浪徒
孤街浪徒 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 19:05

    If you use trunk the machinery is already there. groupBy is defined on Traversable and sum can be applied directly to the list, you don't have to write a fold.

    scala> trades groupBy (_.currency) map { case (k,v) => k -> (v map (_.amount) sum) }
    res1: Iterable[(String, Int)] = List((GBP,10001000), (JPY,10000100), (USD,10010000))
    

提交回复
热议问题