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 myself?
Input:
List((a,4), (b,1), (c,1), (d,1))
List((a,1), (b,1), (c,1))
Expected output:
List((a,5),(b,2),(c,2),(d,1))
You can try the following one-line:
Where
l1andl2are the lists of tuples you want merge.Now, the breakdown:
(l1 ++ l2)you just concatenate both lists.groupBy( _._1)you group all tuples by their first element. You will receive a Map withthe first element as key and lists of tuples starting with this element as values.
.map( kv => (kv._1, kv._2.map( _._2).sum ) )you make a new map, with similar keys, but the values are the sum of all second elements..toListyou convert the result back to a list.Alternatively, you can use pattern matching to access the tuple elements.