Using groupBy
creates a Map
where the values are a list of all matching objects:
scala> list.groupBy(_.shareClass)
res0: scala.collection.immutable.Map[String,List[Test]] = Map(b -> List(Test(b,20), Test(b,5)), a -> List(Test(a,10), Test(a,30)))
From there you can use mapValues
to transform the values of the map, first selecting the noOfShares
attribute and then sum
these:
scala> list.groupBy(_.shareClass).mapValues(_.map(_.noOfShares).sum)
res1: scala.collection.immutable.Map[String,Long] = Map(b -> 25, a -> 40)
Note that mapValues
only creates a view on the original Map
, this means the _.map(_.noOfShares).sum
-part is applied every time the result is accessed (even when assigning it to a val
before). To get a plain Map
with only the result, you can call view.force
on it:
scala> list.groupBy(_.shareClass).mapValues(_.map(_.noOfShares).sum).view.force
res2: scala.collection.immutable.Map[String,Long] = Map(b -> 25, a -> 40)