我有一个案例类,例如:
case class ReportData(
building: Option[String] = None,
serial: Option[String] = None,
`type`: Option[String] = None,
model: Option[String] = None,
machine: Option[String] = None)
和其他领域。
我有这些对象的列表,例如:
val reports = List(report1, report2, report3, report11, report12)
请求是对这些类的特定字段执行一些特定的复杂操作,例如仅通过作为参数接收的字段对这些列表进行分组:groupFields="building,serial"
这是一个很好的小组的例子:
val reportsGroupBoth = reports.groupBy(p => (p.building.getOrElse(""), p.serial.getOrElse("")))
但我想根据收到的字段使其有条件,所以我想的唯一方法是为每个字段分开分组(我稍后会添加,如果我将它们分开,if condition
我只想收到与上述相同的结果,group by
结果是类型:Map[(String, String),List[agile.ReportData]]
所以我尝试了:
// group by building (if building is defined in groupFields list)
val reportsGroup1 = reports.groupBy(p => p.building)
这很好,但这是错误的:
// group by building and serial (if building and serial are in groupFields list)
val reportsGroup2 = reportsGroup1 map {
case (key, value) => (key, value.groupBy(v => v.serial).keys) -> value.groupBy(v => v.serial).values
}
所以问题是如何修改它最终会得到与 tpyereportsGroup2
相同的结果reportsGroupBoth
Map[(String, String),List[agile.ReportData]]