在 scala 中遍历数组的最佳方法是什么

What is the Best way to loop over an array in scala

我是 scala 的新手,我正在尝试重构下面的代码 code.I 想消除下面代码中使用的 "index" 并遍历数组以获取数据。

 subgroupMetricIndividual.instances.foreach { instanceIndividual =>
   val MetricContextListBuffer: ListBuffer[Context] = ListBuffer()
   var index = 0
   contextListBufferForSubGroup.foreach { contextIndividual =>
        MetricContextListBuffer += Context(
                 entity = contextIndividual,
                 value = instanceIndividual(index).toString
        )
        index += 1
   }
}

例如,如果变量的值如下:

contextListBufferForSubGroup = ("context1","context2")
subgroupMetricIndividual.instances = {{"Inst1","Inst2",1},{"Inst3","Inst4",2}}

那么上下文应该是这样的:

  { 
   entity: "context1",
   value:  "Inst1"
   },
   { 
   entity: "context2",
   value:  "Inst2"
   },
   { 
   entity: "context1",
   value:  "Inst3"
   },
   { 
   entity: "context2",
   value:  "Inst4"
   }

注:

instanceIndividual 可以拥有比 contextListBufferForSubGroup 中更多的元素。在这种情况下,我们必须忽略 instanceIndividual 中的最后一个额外元素

您可以将两个列表压缩成一个元组列表,然后映射到它上面。 例如

subgroupMetricIndividual.instances.foreach { instanceIndividual =>
  val MetricContextListBuffer = contextListBufferForSubGroup.zip(instanceIndividual).map {
    case (contextIndividual, instanceIndividualIndex) => Context(
      entity = contextIndividual,
      value = instanceIndividualIndex.toString
    )
  }
}

如果 Context 可以像函数一样调用,即 Context(contextIndividual, instanceIndividualIndex.toString) 那么你可以写得更短。

subgroupMetricIndividual.instances.foreach { instanceIndividual =>
  val MetricContextListBuffer = contextListBufferForSubGroup
    .zip(instanceIndividual.map(_.toString)).map(Context.tupled)
}

在不知道你的确切数据类型的情况下,我模拟了一些可能接近你想要的东西,并且使用地图和不可变集合的功能稍微好一些

case class Context(entity:String, value:String)

val contextListBufferForSubGroup = List("context1","context2")
val subgroupMetricIndividualInstances = List(List("Inst1","Inst2",1),List("Inst3","Inst4",2))

val result: List[Context] = subgroupMetricIndividualInstances.map { instanceIndividual =>
contextListBufferForSubGroup.zip(instanceIndividual) map { case v: (String, String) =>
    Context(
      entity = v._1,
      value = v._2
    )
  }
}.flatten