Last active
August 17, 2016 08:47
-
-
Save Locke/e22e722e0e8c089ccc9e786f26464213 to your computer and use it in GitHub Desktop.
Set[(A, B)] toSetMap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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