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.
In Scala, you can convert a list to a map in Scala using the toMap method. A map contains a set of values i.e. key-> value but a list contains single values. So, while converting a list to map we have two ways, Add index to list.
Scala Map toList() method with exampleThe toList() method is utilized to display the elements of the map in the list. Return Type: It returns all the elements of the map in the list.
map() method is a member of TraversableLike trait, it is used to run a predicate method on each elements of a collection. It returns a new collection.
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)))
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