I would like to take a list of RawDoc which each have a title and a single version and transform it into a list of Doc which each have a title and all its versions collected together into a list:
case class RawDoc(title:String, version:String)
case class Doc(title:String, versions:List[String])
val rawDocs:List[RawDoc] = List(
RawDoc("Green Book", "1.1"),
RawDoc("Blue Book", "1.0"),
RawDoc("Green Book", "1"),
RawDoc("Blue Book", "2")
)
I would like to start with the above rawDocs and create docs like this:
val docs:List[Doc] = List(
Doc("Green Book", List("1.1", "1")),
Doc("Blue Book", List("1.0", "2"))
)
Without using for loops how could this be done in Scala?
This should work:
val docs = rawDocs.
groupBy(_.title).map{
case(title, docsWithSameTitle) =>
Doc(title, docsWithSameTitle.map(_.version))
}
And if the difference between "Blue Book" and "Blue BooK" is not incidental typo and they should be treated as equal:
val docs = rawDocs.
groupBy(_.title.toUpperCase).map{
case(_, docsWithSameTitle) =>
Doc(docsWithSameTitle.head.title, docsWithSameTitle.map(_.version))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With