数组组中2个元素的总和通过多个值

时间:2018-12-11 13:48:05

标签: arrays scala collections

case class test(primary : String, secondary : Array[String], count : Int)

给出数组a1:

a1: Array[test] = Array(test(Speed,Array(VR,ABC),5), test(Speed,Array.Empty[String],2), test(Speed,Array(Another,VR),3), test(Speed,Array(Another),3))

给出数组a2:

a2: Array[test] = Array(test(Speed,Array(VR,ABC),6), test(Speed,Array.Empty[String],5), test(Speed,Array(Another),2), test(Speed,Array(SomethingElse),2))

我需要对计数求和,并将其按主要和次要值分组在new Array[test]中。我该怎么做?这里的计数是主要组和次要组的总和。这2个数组是从2个输入数据生成的统计信息。我的任务是汇总统计信息。

结果应为:

a3: Array[test] = Array(test(Speed,Array(VR,ABC),11), test(Speed,Array.Empty[String],7),test(Speed,Array(Another),5),test(Speed,Array(Another,VR),3),test(Speed,Array(SomethingElse),2))

2 个答案:

答案 0 :(得分:1)

这应该有效:

val a3: Array[test] =
  (a1 ++ a2)
    .groupBy(test => (test.primary, test.secondary))
    .mapValues(_.map(_.count).sum)
    .map { case ((primary, secondary), count) => test(primary, secondary, count) }
    .toArray

结果是:

a3: Array[test] = Array(test(Speed,Another,5), test(Speed,VR,11), test(Speed,,7))

答案 1 :(得分:1)

如果您要求第一个数组包含相同数量的elementami,并且具有相同的主次配对对顺序(例如您的示例),则还可以执行以下操作:

val a3: Array[test] =
    a1.zip(a2)
      .map {
      case (test1, test2)
        if test1.primary == test2.primary &&
          test1.secondary == test2.secondary
      => test(test1.primary, test2.secondary, test1.count + test2.count))
      case _ => throw IllegalStateException
    }

否则,您可能会同时连接列表s和按Okrm建议的主键/辅助键进行分组:

val a3: Array[test] =
  (a1 ++ a2)
    .groupBy(test => (test.primary, test.secondary))
    .mapValues(_.map(_.count).sum)
    .map { case ((primary, secondary), count) => test(primary, secondary, count) }
    .toArray

对于给定的示例,结果应相同(在顺序旁边):

a3: Array[test] = Array(test(Speed,Another,5), test(Speed,VR,11), test(Speed,,7))