Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 644
user1043466 Avatar asked Dec 30 '11 03:12

user1043466


People also ask

How do I convert a list to map in Scala?

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.

Can map be converted into list using toList in Scala?

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.

What does map () do in Scala?

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.


1 Answers

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)))
like image 173
huynhjl Avatar answered Sep 20 '22 21:09

huynhjl