Search code examples
scalasumtuples

How to sum a list of tuples


Given the following list of tuples...

val list = List((1, 2), (1, 2), (1, 2))

... how do I sum all the values and obtain a single tuple like this?

(3, 6)

Solution

  • Using the foldLeft method. Please look at the scaladoc for more information.

    scala> val list = List((1, 2), (1, 2), (1, 2))
    list: List[(Int, Int)] = List((1,2), (1,2), (1,2))
    
    scala> list.foldLeft((0, 0)) { case ((accA, accB), (a, b)) => (accA + a, accB + b) }
    res0: (Int, Int) = (3,6)
    

    Using unzip. Not as efficient as the above solution. Perhaps more readable.

    scala> list.unzip match { case (l1, l2) => (l1.sum, l2.sum) }
    res1: (Int, Int) = (3,6)