Java 8 findFirst()。isPresent()比count()>更有效吗? 0? [英] Is Java 8 findFirst().isPresent() more efficient than count() > 0?
问题描述
鉴于我有一个流 Stream< T> stream = list.stream()。filter(some predicate)
其中列表非常大,通过执行以下操作来检查流是否为空是否更有效: stream .count()> 0
或通过这样做: stream.findFirst()。isPresent()
?
Given I have a stream Stream<T> stream = list.stream().filter(some predicate)
where the list is very large, is it more efficient to check whether the stream is non-empty by doing: stream.count() > 0
or by doing: stream.findFirst().isPresent()
?
推荐答案
如果你想知道的是,是否匹配,你应该使用
list.stream()。anyMatch(some predicate )
,不仅因为它更有效率,而且因为它是表达你意图的正确习惯用语。
If all you want to know, is whether there is a match, you should use
list.stream().anyMatch(some predicate)
, not only because it is more efficient, but also, because it is the correct idiom for expressing you intention.
正如其他人所说的那样, anyMatch
是短路的,这意味着它将在第一场比赛时停止,而 count
将是,名称建议,在返回之前计算所有匹配。根据流内容,这可以产生巨大的性能差异。但请注意,通过使用
list.stream()。filter(some predicate).limit(你可以使
count
同样有效率。 1).count()> 0
As said by others, anyMatch
is short-circuiting, which implies that it will stop at the first match, whereas count
will, as the name suggests, count all matches before returning. Depending on the stream contents, this can make a huge performance difference. But note, that you can make count
similarly efficient, by using
list.stream().filter(some predicate).limit(1).count() > 0
然后,它也将在第一次出现后停止,但如上所述, anyMatch
仍然是表达您是否有任何匹配感兴趣的首选方式。当任务是要找出至少 n
匹配时,事情会发生变化。然后, .limit(n).count()> n-1
(或> = n
)成为自然习语。
Then, it will also stop after the first occurrence, but, as said, anyMatch
is still the preferred way to express that you are interested in whether there is any match. Things change, when the task is to find out whether there are at least n
matches. Then, .limit(n).count() > n-1
(or >= n
) becomes the natural idiom.
请注意, findFirst()
与其他解决方案不同,因为它的答案取决于排序。因此,如果您只想知道是否匹配,则应使用 findAny()
。尽管如此,由于需要返回匹配值,还有一个理论差异,只是告诉是否存在匹配,例如 anyMatch
,但目前只有这种差异在可选
实例的构造中,因此可以忽略不计。
Note that findFirst()
differs from the other solution because its answer depends on the ordering. So if you only want to know whether there is a match, you should use findAny()
instead. Still, there is a theoretical difference due to the requirement of returning the matching value, compared to just telling whether there is a match, like anyMatch
does, though currently that difference lies only in the construction of an Optional
instance, hence is negligible.
但是因为你正在编写一个API来编码你的意图,当你只想知道是否匹配时,你不应该使用 find ...
。 anyMatch
清楚地表达了您的意图,并可能在未来的实施或更复杂的情况下获得更高的利益。
But since you are programming against an API to encode your intention, you should not use find…
when you only want to know whether there is a match. anyMatch
clearly expresses your intention and might have an even higher benefit in future implementations or more complex scenarios.
这篇关于Java 8 findFirst()。isPresent()比count()>更有效吗? 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!