如何在列表中查找匹配元素并将其映射为 Scala API 方法?
有没有一种方法可以执行以下操作而不执行这两种方法:find
和map
?
val l = 0 to 3
l.find(_ * 33 % 2 == 0).map(_ * 33) // returns Some(66)
Is there a method to do the following without doing both methods: find
and map
?
val l = 0 to 3
l.find(_ * 33 % 2 == 0).map(_ * 33) // returns Some(66)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用收集怎么样?
但是,这将返回所有匹配项,而不仅仅是第一个匹配项。
更好的答案是基于 Scala 2.9:恐怕
评论中建议的解决方案是附加一个
head
来获取 Scala 2.8 版本,效率不是很高。也许在那种情况下我会坚持你自己的代码。无论如何,为了确保它返回一个选项,您不应该调用head
,而应该调用headOption
。How about using collect?
However that will return all matches and not just the first one.
The better answer would have been, based on Scala 2.9:
The solution suggested in the comments to append a
head
to get a Scala 2.8 version of that is not very efficient, I'm afraid. Perhaps in that case I would stick to your own code. In any case, in order to make sure it returns an option, you should not callhead
, butheadOption
.如果您不想多次执行
map()
操作(例如,如果这是一次昂贵的数据库查找),您可以这样做:l.view.map(_ * 33) .find(_ % 2 == 0)
view
使集合变得惰性,因此map()
操作的数量被最小化。If you don't want to do your
map()
operation multiple times (for instance if it's an expensive DB lookup) you can do this:l.view.map(_ * 33).find(_ % 2 == 0)
The
view
makes the collection lazy, so the number ofmap()
operations is minimized.嘿看,又是我的小伙伴
findMap
!请注意,与已接受的答案不同,但就像其注释中提到的
collectFirst
方法一样,这个人一旦找到匹配的元素就会停止。Hey look, it's my little buddy
findMap
again!Note that, unlike in the accepted answer, but like the
collectFirst
method mentioned in one of its comments, this guy stops as soon as he finds a matching element.这可以做到,但如果你告诉你真正想要实现的目标会更容易:
This can do it, but it would be easier if you tell what you're really trying to achieve: