Tuesday, 3 September 2013

Conditional group by in Scala

Conditional group by in Scala

I have a case class like:
case class ReportData(
building: Option[String] = None,
serial: Option[String] = None,
`type`: Option[String] = None,
model: Option[String] = None,
machine: Option[String] = None)
and other fields too.
I have a list of these objects, for instance:
val reports = List(report1, report2, report3, report11, report12)
The request is to do some specific complex operations with specific fields
of these class, for instance group these list only by the fields received
as a parameter: groupFields="building,serial"
This is an example of a fine group by:
val reportsGroupBoth = reports.groupBy(p => (p.building.getOrElse(""),
p.serial.getOrElse("")))
butI want to make it conditional depending of the fields received so the
only way I am thinking is to make group by separated for each field (I
will add if condition later now I just want to receive the same result as
the above group by if I make them separated, result being of type:
Map[(String, String),List[agile.ReportData]]
so I tried:
val reportsGroup1 = reports.groupBy(p => p.building)
which is fine but this one is wrong:
val reportsGroup2 = reportsGroup1 map { case (key, value) => (key,
value.groupBy(v => v.serial).keys) -> value.groupBy(v => v.serial).values
}
So the question is how to modify reportsGroup2 that in the end it will
have the same result as Map[(String, String),List[agile.ReportData]]

No comments:

Post a Comment