Skip to content

Instantly share code, notes, and snippets.

@gandalftheFFFFFF
Created January 4, 2018 16:55
Show Gist options
  • Save gandalftheFFFFFF/ad2a7ad6024f7ed529c110d567cfab4d to your computer and use it in GitHub Desktop.
Save gandalftheFFFFFF/ad2a7ad6024f7ed529c110d567cfab4d to your computer and use it in GitHub Desktop.
How to convert flat data to structured case classes
case class B(name: String)
case class A(name: String, seq: Seq[B])
case class X(name: String, seq: Seq[A])
val data: Seq[Tuple3[String, String, String]] = Seq(
("X", "Left", "Some value"),
("X", "Left", "Some other value"),
("X", "Right", "A third value"),
("X", "Right", "Fourth value")
)
val structuredData = X("X", Seq(
A("A", Seq(
B("Some value"),
B("Some other value")
)),
A("B", Seq(
B("A third value"),
B("Fourth value")
))
))
println(structuredData)
val structuredByUglyCode = data
.groupBy(_._1) // group by "X"
.mapValues(_.groupBy(_._2)) // group by "Left" and "Right"
.mapValues(_.mapValues(_.map(t => B(t._3)))) // Remove the grouped values from inner-most tuple and map to B
.mapValues(_.map { case (k, v) => A(k, v) }) // middle layer from `"Left" -> List(B("Some value"), B("Some other value"))` to `A(....)
.map { case (k, v) => X(k, v.toSeq) } // Map outer-most layer to List(X(...))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment