Lai Yu-Hsuan Lai Yu-Hsuan - 19 days ago 5x
Scala Question

Find the first element that satisfies condition X in a Seq

Generally, how to find the first element satisfying certain condition in a


For example, I have a list of possible date format, and I want to find the parsed result of first one format can parse my date string.

val str = "1903 January"
val formats = List("MMM yyyy", "yyyy MMM", "MM yyyy", "MM, yyyy")
.map(new SimpleDateFormat(_))
formats.flatMap(f => {try {
}catch {
case e: Throwable => None

Not bad. But 1. it's a little ugly. 2. it did some unnecessary work(tried
"MM yyyy"
"MM, yyyy"
formats). Perhaps there is more elegant and idiomatic way? (using


If you're confident at least one will format will succeed:{format => Try(format.parse(str)).toOption}.filter(_.isDefined).head

If you want to be a bit safer:{format => Try(format.parse(str)).toOption}.find(_.isDefined)

Try was introduced in Scala 2.10.

A view is a type of collection that computes values lazily. It will apply the code within the Try to only as many items in the collection as is necessary to find the first one that is defined. If the first format applies to the string, then it won't try to apply the remaining formats to the string.