Created
September 2, 2011 16:37
-
-
Save daithiocrualaoich/1189097 to your computer and use it in GitHub Desktop.
Scala Collections Pimp to add distinctBy(hash: ... => ...) for hash filterings
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
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