Java 8 中 findAny() 和 findFirst() 的区别 [英] Difference between findAny() and findFirst() in Java 8

查看:37
本文介绍了Java 8 中 findAny() 和 findFirst() 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

解决方案

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

这不是真的.根据 javadoc,Stream#findAny():

<块引用>

返回一个 Optional 描述流的some 元素,或者一个空的可选 如果流为空.此操作的行为明显是不确定的;可以自由选择流中的任何元素.这是为了最大限度地提高并行操作的性能;

Stream.findFirst() 将返回一个 Optional 描述严格流的第一个元素.Stream 类没有 .findOne() 方法,所以我想你的意思是 .findFirst().

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 the 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?

That's not true. According to the 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;

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆