Generally, how to find the first element satisfying certain condition in a Seq
?
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 {
Some(f.parse(str))
}catch {
case e: Throwable => None
}}).head
Not bad. But 1. it's a little ugly. 2. it did some unnecessary work(tried "MM yyyy"
and "MM, yyyy"
formats). Perhaps there is more elegant and idiomatic way? (using Iterator
?)