Scala-如何筛选嵌套集合结构?

Scala-如何筛选嵌套集合结构?,scala,collections,Scala,Collections,以下是我的案例课程: case class Metric ( id: Long, name: String, features: List[Feature] ) case class Feature ( featureId: Long, name: String, value: String, processTime: Timestamp ) 每个指标都有一个列表[功能]。我想过滤每个指标,使其列表[功能]仅包含每个功能ID的最新功能 我尝试了以下操作,但它返回了一个jut列表[immuta

以下是我的案例课程:

case class Metric (
id: Long,
name: String,
features: List[Feature]
)

case class Feature (
featureId: Long,
name: String,
value: String,
processTime: Timestamp
)
每个指标都有一个
列表[功能]
。我想过滤每个指标,使其
列表[功能]
仅包含每个
功能ID
的最新功能

我尝试了以下操作,但它返回了一个jut
列表[immutable.Iterable[Feature]]
,其中正确过滤了功能。但我需要它重新创建一个
列表[Metric]
,其中包含过滤后的功能列表

val f1 = Feature(1, "f1", "v1", Timestamp.valueOf("2019-07-01 00:00:00"))
val f2 = Feature(1, "f2", "v2", Timestamp.valueOf("2019-07-05 00:00:00"))
val f3 = Feature(2, "f3", "v3", Timestamp.valueOf("2019-03-07 00:00:00"))
val f4 = Feature(2, "f4", "v4", Timestamp.valueOf("2019-03-10 00:00:00"))

val metric1 = Metric(1, "m1", List(f1, f2, f3, f4))
val metric2 = Metric(1, "m1", List(f3, f4))

val metricsList = List(metric1, metric2)

val newMetrics = metricsList.map(m => m.features.groupBy(_.featureId)
  .map { case (featureId, metricsList) => metricsList.reduce {
    (m1: Feature, m2: Feature) => if (m1.processTime.after(m2.processTime)) m1 else m2
  }
  })
UPD:预期输出是一个
列表(metric1、metric2)
其中


val metric1=Metric(1,“m1”,List(f2,f4))
val metric2=Metric(1,“m1”,List(f4))
您可以在
Metric
类上使用case类
copy
方法来完成此操作。这将创建一个带有过滤特征的
Metric
的新实例。请注意,您也可以使用
maxBy
,因此不需要使用
reduce
。为此,您需要提供一个
排序
隐式排序时间戳。下面的代码应该满足您的要求:

implicit def ordered: Ordering[Timestamp] = new Ordering[Timestamp] {
  def compare(x: Timestamp, y: Timestamp): Int = x compareTo y
}

val newMetrics = metricsList.map(m => {
  val features = m.features.groupBy(_.featureId).mapValues(_.maxBy(_.processTime)).values
  m.copy(features = features.toList)
})

您可以在
度量
类上使用case class
copy
方法来实现这一点。这将创建一个带有过滤特征的
Metric
的新实例。请注意,您也可以使用
maxBy
,因此不需要使用
reduce
。为此,您需要提供一个
排序
隐式排序时间戳。下面的代码应该满足您的要求:

implicit def ordered: Ordering[Timestamp] = new Ordering[Timestamp] {
  def compare(x: Timestamp, y: Timestamp): Int = x compareTo y
}

val newMetrics = metricsList.map(m => {
  val features = m.features.groupBy(_.featureId).mapValues(_.maxBy(_.processTime)).values
  m.copy(features = features.toList)
})

您可以发布预期输出吗?@Vamsi我已经用预期输出更新了问题。您可以发布预期输出吗?@Vamsi我已经用预期输出更新了问题