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
?)
Just use find method as it returns an Option of the first element matching predicate if any :
Moreover, execution stops at the first match, so that you don't try parsing every element of your set before picking the first one. Here is an example :
Note that for Stream it doesn't really matter. Also if you are using IntelliJ for example it will suggest you :