Skip to content

Instantly share code, notes, and snippets.

@daithiocrualaoich
Created September 2, 2011 16:37
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daithiocrualaoich/1189097 to your computer and use it in GitHub Desktop.
Save daithiocrualaoich/1189097 to your computer and use it in GitHub Desktop.
Scala Collections Pimp to add distinctBy(hash: ... => ...) for hash filterings
implicit def seq2Distinct[T, C[T] <: Seq[T]](tees: C[T]) = new {
import collection.generic.CanBuildFrom
import collection.mutable.{HashSet => MutableHashSet}
def distinctBy[S](hash: T => S)(implicit cbf: CanBuildFrom[C[T],T,C[T]]): C[T] = {
val builder = cbf()
val seen = MutableHashSet[S]()
for (t <- tees) {
if (!seen(hash(t))) {
builder += t
seen += hash(t)
}
}
builder.result
}
}
case class Content(id: Int, body: String)
val test = List(Content(1,"1"), Content(1,"2"), Content(2,"2"), Content(2,"2"), Content(3,"3"), Content(4,"4"), Content(5,"5"))
test.distinct
test distinctBy { _.id }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment