简体   繁体   中英

Transform list in to map of element -> list(element) in scala

I have a list of documents, where a Document has an owner which is a User.

What is the most elegant way of transforming this list into a Map of Users to the List of Documents that they own?

So for example I have:

"doc1" owned by user "John"
"doc2" owned by user "Frank"
"doc3" owned by user "John"

I should end up with a map of:

"John" -> List("doc1", "doc3"), "Frank" -> List("doc2")

I can think of one way which would be to grab all unique users from the documents and for each of them filter the document list to just be the ones they own, but I'm wondering if there's a way that uses a fixed number of passes through the list to prevent any performance problems if the list is big.

Use groupBy:

scala> case class Doc(id: String, owner: String)
defined class Doc

scala> List(Doc("doc1", "John"), Doc("doc2", "Frank"), Doc("doc3", "John"))
res0: List[Doc] = List(Doc(doc1,John), Doc(doc2,Frank), Doc(doc3,John))

scala> res0.groupBy(_.owner)
res1: scala.collection.immutable.Map[String,List[Doc]] = Map(
  Frank -> List(Doc(doc2,Frank)), John -> List(Doc(doc1,John), Doc(doc3,John)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM