简体   繁体   English

Scala元组序列比较

[英]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. 在只有一种类型和一个值的意义上,第二个元组是groupedBy元组。 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: 在上面的示例中,首先需要为Type添加t1并添加值,然后得出:

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

Now groupedT1 needs to be added the same way to t2. 现在,必须以相同的方式将groupedT1添加到t2。 I used the groupBy function as my starting point and applied that on t1 which gave me: 我使用groupBy函数作为起点,并将其应用于t1,这给了我:

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. 要得出结果,我知道我必须对元组执行mapValues和foldLeft操作,以便可以返回聚合结果,但我只是无法正确获取语法。 Any help or any better idea? 有帮助或更好的主意吗?

这个给你:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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