Skip to content

Instantly share code, notes, and snippets.

@dlwh
Created September 3, 2014 01:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dlwh/74a9d2280afe94683830 to your computer and use it in GitHub Desktop.
Save dlwh/74a9d2280afe94683830 to your computer and use it in GitHub Desktop.
toMultiMap
implicit class scEnrichColl[Coll <: Traversable[(_,_)]](val __this: Coll) extends AnyVal {
def toMultiMap[Result, A, B](implicit view: Coll <:< Traversable[(A, B)], cbf: CanBuildFrom[Coll, B, Result]): Map[A, Result] = {
var result = collection.mutable.Map[A, mutable.Builder[B, Result]]()
result = result.withDefault { a => val r = cbf(__this); result.update(a, r); r}
for((a,b) <- view(__this)) {
result(a) += b
}
result.mapValues(_.result()).toMap
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment