在 Seq 中找到满足条件 X 的第一个元素 [英] Find the first element that satisfies condition X in a Seq

查看:23
本文介绍了在 Seq 中找到满足条件 X 的第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般来说,如何在Seq中找到满足一定条件的第一个元素?

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

还不错.但是 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?)

推荐答案

如果您确信至少有一个格式会成功:

If you're confident at least one will format will succeed:

formats.view.map{format => Try(format.parse(str)).toOption}.filter(_.isDefined).head

如果你想更安全一点:

formats.view.map{format => Try(format.parse(str)).toOption}.find(_.isDefined)

Try 是在 Scala 2.10 中引入的.

Try was introduced in Scala 2.10.

A view 是一种类型惰性计算值的集合.它会将 Try 中的代码应用到集合中找到定义的第一个项目所需的尽可能多的项目.如果第一个 format 适用于字符串,则它不会尝试将其余格式应用于字符串.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆