我是scala的新手,我正在尝试重构下面的代码。我想消除下面代码中使用的“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}}
那么Context应该是这样的:
{
entity: "context1",
value: "Inst1"
},
{
entity: "context2",
value: "Inst2"
},
{
entity: "context1",
value: "Inst3"
},
{
entity: "context2",
value: "Inst4"
}
注意:
instanceIndividual可以拥有比contextListBufferForSubGroup中更多的元素。在这种情况下,我们必须忽略instanceIndividual中的最后一个额外元素
答案 0 :(得分:1)
您可以将两个列表压缩为元组列表,然后将其映射到该列表。 e.g。
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)
}
答案 1 :(得分:1)
在不知道您的确切数据类型的情况下,我嘲笑了一些可能与您想要的内容相近的东西,并且使用地图和不可变集合稍微更具功能性
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