Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

Difference between findAny() and findFirst() in Java 8

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...