Skip to content

Instantly share code, notes, and snippets.

@Locke
Last active August 17, 2016 08:47
Show Gist options
  • Save Locke/e22e722e0e8c089ccc9e786f26464213 to your computer and use it in GitHub Desktop.
Save Locke/e22e722e0e8c089ccc9e786f26464213 to your computer and use it in GitHub Desktop.
Set[(A, B)] toSetMap
/*
I needed a quick transformation like `toMap` on Set[(A, B)] that retains all of B's values.
Thanks to https://twitter.com/br_waldteufel/status/765831435244670976 this is now much cleaner than the first revision :)
example:
scala> Set(("A", 1), ("A", 2), ("B", 1)).toSetMap
res0: Map[String,Set[Int]] = Map(A -> Set(1, 2), B -> Set(1))
*/
object Helper {
def setToMapOfSets[A, B](x: Set[(A, B)]): Map[A, Set[B]] = {
x.groupBy(_._1).mapValues(_.map(_._2))
}
implicit class richSeqSet[A, B](self: Set[(A, B)]) {
def toSetMap: Map[A, Set[B]] = setToMapOfSets(self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment