An elegant way to express xs.sort.head

Several combinations of methods in a collection can be expressed more briefly in Scala. For example, xs.filter(f).headOptionyou can express how xs.find(f), but xs.map.filterusually it is better to express through xs.collect.

I find myself writing xs.sortWith(f).head, and it seems to me like something that can be expressed as a single method, "find me the smallest item in this collection, according to this sorting function."

However, I do not see obvious methods on Seqor TraversableLike. Is there one method that reflects my intention, or a .sort.headmore elegant way to find the "smallest" element?

+3
source share
1 answer
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
+13
source

All Articles