0
votes

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 :)

2

2 Answers

2
votes

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)
1
votes
list.groupBy(_._1).mapValues(_.map(_._2).sum)

which can be written as

list.groupBy(_._1).mapValues { tuples => 
  val ints = tuples.map { case (c, i) => i }
  ints.sum
}