CW Holeman II
CW Holeman II

Reputation: 4961

Transform a list List[String, String] into List[String, List[String]] in Scala?

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?

Upvotes: 3

Views: 176

Answers (2)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340708

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))
  }

Upvotes: 5

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297155

rawDocs.groupBy(_.title).mapValues(_ map (_.version)).map { 
  case (title, versions) => Doc(title, versions) 
}

Upvotes: 4

Related Questions