I have two lists in Scala, how to merge them such that the tuples are grouped together?
Is there an existing Scala list API which can do this or need I do it by myse
Alternatively you can also use mapValues to shorten the code.
mapValues, as you can probably guess, allows you to re-map just the value for each (key, value) pair in the Map created by groupBy.
In this case the function passed to mapValues reduces each (Char, Int) tuple to just the Int then sums the resulting List of Ints.
(l1 ::: l2).groupBy(_._1).mapValues(_.map(_._2).sum).toList
If the order of the output list needs to follow your example, just add sorted which relies on an Ordering[(Char, Int)] implicit instance.
(l1 ::: l2).groupBy(_._1).mapValues(_.map(_._2).sum).toList.sorted