Skip to content

Instantly share code, notes, and snippets.

@liorgonnen
Last active August 29, 2015 14:05
Show Gist options
  • Save liorgonnen/799707bc56e8fbb903fd to your computer and use it in GitHub Desktop.
Save liorgonnen/799707bc56e8fbb903fd to your computer and use it in GitHub Desktop.
Filter a collection of objects by values of a specific object field
package utils
import scala.collection.generic.CanBuildFrom
import scala.collection.{SeqLike, mutable}
/**
* Created by Lior Gonnen on 8/17/14.
*/
object CollectionUtils {
implicit class ExtendedSeqLike[A, Repr](seqLike : SeqLike[A, Repr]) {
/**
* Returns a new collection with distinct objects in relation to the function f<br/>
* Used mainly to get filter objects based on a distinct onject field
*
* @example
* case class Person(name : String, age : Int)<br/>
* val people = List(Person("Joe", 28), Person("Jennifer", 35), Person("Jane", 22))<br/>
* val filtered = people.distinctBy(_.age < 30)<br/>
*
* @param f A function that maps object to the desired unique representation
* @param cbf Implicit factory builder
* @tparam B The type of the returned collection
* @return A new collection with distinct objects in relation to f
*/
def distinctBy[B](f : A => B)(implicit cbf : CanBuildFrom[Repr, A, Repr]) : Repr = {
val builder = cbf(seqLike.repr)
val seen = mutable.HashSet[B]()
for (x <- seqLike) {
val fx = f(x)
if (!seen(fx)) {
builder += x
seen += fx
}
}
builder.result()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment