Michał Michał - 2 months ago 6
Scala Question

How to sum a List[(Char,Int)] into a Map[Char,Int] in Scala?

I've got list of pairs:

List(('a',3),('b',3),('a',1))


and I would like to transform it by grouping by _1 and summing _2. The result should be like

Map('a'->4, 'b' -> 3)


I very new to Scala so please be kind :)

Answer

More direct version. We fold over the list, using a Map as the accumulator. The withDefaultValue means we don't have to test if we have the entry in the map already.

val xs =  List(('a',3),('b',3),('a',1))

xs.foldLeft(Map[Char, Int]() withDefaultValue 0)
           {case (m, (c, i)) => m updated (c,m(c)+i)}

//> res0: scala.collection.immutable.Map[Char,Int] = Map(a -> 4, b -> 3)
Comments