Java 8中findAny()和findFirst()之间的区别 [英] Difference between findAny() and findFirst() in Java 8
问题描述
我对 Stream#findAny()
和
java 8中的API。的流#findFirst()
感到困惑$ c> Stream
I am little confused between Stream#findAny()
and Stream#findFirst()
of the Stream
API in java 8.
我所理解的是两者都会从流中返回第一个匹配的元素,例如,当与过滤器一起使用时?
What I understood is that both will return the first matched element from the stream, for example, when used in conjunction with filter?
那么,为什么两种方法可以完成同样的任务呢?我错过了什么吗?
So, why two methods for same task? Am I missing something?
推荐答案
我的理解是两者都会返回第一个匹配的元素
来自流,例如,当与过滤器一起使用时?
What I understood is that both will return the first matched element from the stream, for example, when used in conjunction with filter?
这不是真的。根据javadoc, Stream#findAny()
:
That's not true. According to the javadoc, Stream#findAny()
:
返回
可选< T>
描述流的某些元素,或空
可选< T>
如果流是空的。
此操作的行为明确是不确定的; 可以自由选择流中的任何元素。这是为了在并行操作中实现最大性能;
Returns an
Optional<T>
describing some element of the stream, or an emptyOptional<T>
if the stream is empty. The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations;
Stream.findFirst()
将返回可选< T>
,描述严格第一个元素的流。 Stream
类没有 .findOne()
方法,所以我想你的意思是 .findFirst()
。
while Stream.findFirst()
will return an Optional<T>
describing strictly the first element of the stream. The Stream
class doesn't have a .findOne()
method, so I suppose you meant .findFirst()
.
这篇关于Java 8中findAny()和findFirst()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!