kaffein
kaffein

Reputation: 1766

How to transform a List[Tuple2[X,Y]] to a Map[X, List[Y]] to avoid duplicates in Scala?

I am trying to figure out how to transform a List of tuples to a Map using groupBy. Let's say I am retrieving the list from DB this way :

val results: List[(Author, Book)] = getAuthorAndBook()

since, an author may have written many books, I may have the same author with different books in this list so I would like to group the books by author and have a Map[Author, List[Book]] instead.

how can I achieve that ?

I know I have to group but then after that, I am not quite sure how to deal with the Books

results.groupBy(_._1) // and then what ?

any help would be appreciated.

thanks guys

Upvotes: 1

Views: 78

Answers (2)

Sebastien Lorber
Sebastien Lorber

Reputation: 92150

There's a build-in function that does it for lists of Tuple2.

val list = List( (1,"toto") , (2,"test") )
list: List[(Int, java.lang.String)] = List((1,toto), (2,test))

list.toMap
res0: scala.collection.immutable.Map[Int,java.lang.String] = Map((1,toto), (2,test))

You don't need what wingedsubmariner suggest, it's already handled for you.

Upvotes: -1

wingedsubmariner
wingedsubmariner

Reputation: 13667

You can do:

results.groupBy(_._1).mapValues(_.map(_._2))

groupBy creates a Map with the desired keys, but the values still have the keys in them, they are List[(X, Y)] instead of List[Y]. The mapValues call fixes this.

Upvotes: 2

Related Questions