简体   繁体   中英

Scala Tuple Sequence Comparison

I have two Sequence of tuples that contain a type and an integer as the first and second values. The second tuple is a groupedBy tuple in the sense that there is only one type and one value. The first tuple may contain multiple elements with the same type and a different value. What I need to do it to groupBy the first tuple based on the type and add the results of the values that belong to the same type and then aggregate this with the second sequence of tuples. If the first sequence contains a new element that is not contained in the second sequence, it needs to be added to the second sequence.

val t1 = Seq[(TypeA, 1), (TypeB, 2), (TypeA, 3), (TypeC, 5)]
val t2 = Seq[(TypeA, 2), (TypeB, 4)]

From the example above, t1 needs to be first goruped for the Type and the values be added which would then give me:

val groupedT1 = Seq[(TypeA, 4), (TypeB, 2), (TypeC, 5)]

Now groupedT1 needs to be added the same way to t2. I used the groupBy function as my starting point and applied that on t1 which gave me:

t1.groupBy(_._1) // Gave me a Map(TypeA -> ArraySeq((TypeA, 1), (TypeA, 3)), TypeB.... and so on)

To arrive at my result, I know that I have to do a mapValues and a foldLeft operation on the tuple so that I can get the aggregated result back, but I'm just not able to get the syntax right. Any help or any better idea?

这个给你:

val result = t1.groupBy(_._1).mapValues(_.foldLeft(0)((sum, current) => sum + current._2))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM