BJ Peter DeLaCruz BJ Peter DeLaCruz - 3 months ago 7
Scala Question

Combining elements in a Scala list

How do I combine elements in a list, e.g.

List(('h', 1), ('i', 1), ('h', 1), ('i', 1), ('l', 2))


such that I get the following result:

List(('h', 2), ('i', 2), ('l', 2))


Basically, I want to sum the numbers associated with each letter, and the letter should appear in the list only once.

Answer
val myList = List(('h', 1), ('i', 3), ('h', 5), ('i', 7), ('l', 2))
myList.groupBy(_._1).mapValues(_.foldLeft(0)(_ + _._2)).toList
res0: List[(Char, Int)] = List((h,6), (i,10), (l,2))
Comments