Rather than using a mutable HashMap
to build up your Map
, you can just use scala collections' built in groupBy
function. This creates a map from the grouping property to a list of the values in that group, which can then be aggregated, e.g. by taking a sum:
def percentages: Map[String, Double] = {
val t = total
quantities.groupBy(_.name).mapValues(_.map(_.amount).sum / t)
}
This pipeline transforms your List[Quantity]
=> Map[String, List[Quantity]]
=> Map[String, Double]
giving you the desired result.