Skip to content

Instantly share code, notes, and snippets.

@OlegIlyenko
Created March 27, 2010 01:49
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 OlegIlyenko/345638 to your computer and use it in GitHub Desktop.
Save OlegIlyenko/345638 to your computer and use it in GitHub Desktop.
minBy and maxBy for Traversable
println("Sorted: " + list.sortBy(_.balance))
println("Max: " + list.maxBy(_.balance))
println("Min: " + list.minBy(_.balance))
// implicits
class RichTraversable[T](t: Traversable[T]) {
def maxBy[B](fn: T => B)(implicit ord: Ordering[B]) = t.max(ord on fn)
def minBy[B](fn: T => B)(implicit ord: Ordering[B]) = t.min(ord on fn)
}
implicit def toRichTraversable[T](t: Traversable[T]) = new RichTraversable(t)
// example
case class Account(val balance: Int)
val list = List(Account(100), Account(250), Account(35), Account(410), Account(112))
println("Sorted: " + list.sortBy(_.balance))
println("Max: " + list.maxBy(_.balance))
println("Min: " + list.minBy(_.balance))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment