gpt4 book ai didi

java - Java 8 中 findAny() 和 findFirst() 的区别

转载 作者:IT老高 更新时间:2023-10-28 13:53:31 33 4
gpt4 key购买 nike

我对 Java 8 中 Stream API 的 Stream#findAny()Stream#findFirst() 有点困惑。

我的理解是两者都会从流中返回第一个匹配的元素,例如,当与过滤器结合使用时?

那么,为什么同一个任务有两种方法呢?我错过了什么吗?

最佳答案

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() :

Returns an Optional<T> describing some element of the stream, or an empty Optional<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() 将返回 Optional<T> 严格描述流的第一个元素。 Stream类没有 .findOne()方法,所以我想你的意思是 .findFirst() .

关于java - Java 8 中 findAny() 和 findFirst() 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35359112/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com