对于可能为空的 Seq,使用 Option[T] 的最小值/最大值? [英] Min/max with Option[T] for possibly empty Seq?
问题描述
我正在做一些 Scala 体操,其中我有 Seq[T]
,我试图在其中找到最小"元素.这就是我现在所做的:
I'm doing a bit of Scala gymnastics where I have Seq[T]
in which I try to find the "smallest" element. This is what I do right now:
val leastOrNone = seq.reduceOption { (best, current) =>
if (current.something < best.something) current
else best
}
它工作得很好,但我不太满意 - 这么简单的事情有点长,而且我不不太关心如果".使用 minBy
会更优雅:
It works fine, but I'm not quite satisfied - it's a bit long for such a simple thing, and I don't care much for "if"s. Using minBy
would be much more elegant:
val least = seq.minBy(_.something)
... 但是 min
和 minBy
在序列为空时抛出异常.是否有一种惯用的、更优雅的方式来查找可能为空的列表的最小元素作为 Option
?
... but min
and minBy
throw exceptions when the sequence is empty. Is there an idiomatic, more elegant way of finding the smallest element of a possibly empty list as an Option
?
推荐答案
Starting Scala 2.13
, minByOption
/maxByOption
现在是标准库的一部分,如果序列为空,则返回 None
:
Starting Scala 2.13
, minByOption
/maxByOption
is now part of the standard library and returns None
if the sequence is empty:
seq.minByOption(_.something)
List((3, 'a'), (1, 'b'), (5, 'c')).minByOption(_._1) // Option[(Int, Char)] = Some((1,b))
List[(Int, Char)]().minByOption(_._1) // Option[(Int, Char)] = None
这篇关于对于可能为空的 Seq,使用 Option[T] 的最小值/最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!