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)
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)
Using the
foldLeft
method. Please look at the scaladoc for more information.Using
unzip
. Not as efficient as the above solution. Perhaps more readable.Scalaz solution (suggestied by Travis and for some reason a deleted answer):
which outputs
You can solve this using
Monoid.combineAll
from thecats
library:You can see more about this in the cats documentation or Scala with Cats.
answering to this question while trying to understand aggregate function in spark
Here is the link to the SO QA that helped to understand and answer this [Explain the aggregate functionality in Spark
Very easy:
(list.map(_._1).sum, list.map(_._2).sum)
.