在Seq中找到满足条件X的第一个元素 [英] Find the first element that satisfies condition X in a Seq
问题描述
一般来说,如何在 Seq
?
中找到满足特定条件的第一个元素例如,I有一个可能的日期格式的列表,我想找到第一个格式的解析结果可以解析我的日期字符串。
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
不错。但是1.它有点丑陋。 2.做了一些不必要的工作(尝试MM yyyy
和MM,yyyy
格式)。也许有更优雅和惯用的方式? (使用 Iterator
?)
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
?)
推荐答案
一个将格式化将成功:
formats.view.map{format => Try(format.parse(str)).toOption}.filter(_.isDefined).head
如果你想要有点安全:
formats.view.map{format => Try(format.parse(str)).toOption}.find(_.isDefined)
尝试
在Scala 2.10中引入。
Try
was introduced in Scala 2.10.
A view
是一种可以延迟计算值的集合。它会将 Try
中的代码应用于集合中与找到所定义的第一个项目所必需的一样多的项目。如果第一个格式
适用于字符串,那么它不会尝试将剩余的格式应用于字符串。
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.
这篇关于在Seq中找到满足条件X的第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!