Elegant way to express xs.sort.head

collections, scala

Solution

scala> val xs = List("hello", "bye", "hi")
xs: List[java.lang.String] = List(hello, bye, hi)

scala> xs.sortWith(_.length < _.length).head
res10: java.lang.String = hi

scala> xs.min(Ordering.fromLessThan[String](_ > _))
res11: java.lang.String = hi

scala> xs.min(Ordering.by((_: String).length))
res12: java.lang.String = hi

scala> xs.minBy(_.length)
res13: java.lang.String = hi

Problem

Several combinations of methods on a collection can be expressed more succinctly in Scala. For example, `xs.filter(f).headOption` can be expressed as `xs.find(f)`, and `xs.map.filter` can usually be better expressed through `xs.collect`. I find myself writing `xs.sortWith(f).head`, and this feels to me like the sort of thing that could be expressed as a single method, "find me the least element in this collection, according to this sorting function". However, I can't see any obvious methods on `Seq` or `TraversableLike`. Is there a single method that captures my intent, or is `.sort.head` the more elegant way to find the "least" element?

Original source