Difference between anyMatch and findAny in java 8
16,622
They do the same job internally, but their return value is different. Stream#anyMatch()
returns a boolean
while Stream#findAny()
returns an object which matches the predicate.
Author by
Mehraj Malik
Updated on June 13, 2022Comments
-
Mehraj Malik almost 2 years
I have an
Array
and want to perform some matching on it's element.I came to know that it could be done in two ways in
java 8
:String[] alphabet = new String[]{"A", "B", "C"};
anyMatch :
Arrays.stream(alphabet).anyMatch("A"::equalsIgnoreCase);
findAny :
Arrays.stream(alphabet).filter("a"::equalsIgnoreCase) .findAny().orElse("No match found"));
As I can understand both are doing the same work. However, I could not found which one to prefer?
Could someone please make it clear what is the difference between both of them.
-
Jorn Vernee almost 7 yearsThey almost do the same work.
anyMatch
is a short-circuit operation, butfilter
will always process the whole stream. -
Dariusz almost 7 years@JornVernee are you entirely certain of that statement? As far as I remember streams are "lazy", which, for sequential streams, means that after encountering the first matching value in anyMatch it will be returned and the filter will not be processed further.
-
Jorn Vernee almost 7 yearsHmm, I suppose you are right. At least it depends on the implementation. I'm going of the documentation here, where only
anyMatch
explicitly mentions that it's a short-circuit operation. -
Eugene almost 7 years@JornVernee findAny code :
if (!stop && predicate.test(t) == matchKind.stopOnPredicateMatches) { stop = true; ...
it is short-circuiting. -
Jorn Vernee almost 7 years@Eugene is that the JDK9 implementation? The
findAny
I have doesn't accept a predicate -
Eugene almost 7 years@JornVernee that's the third time this week! :( yes, it is jdk-9; that's the default I have. sorry
-
Jorn Vernee almost 7 years@MehrajMalik Well, it's supposed to come out on 2017/07/27 That's not too long from now.
-
Dariusz almost 7 years@JornVernee I checked, take a look at stackoverflow.com/questions/44180155/…
-
Eugene almost 7 years@JornVernee you might have some "substance" here. One is implemented via
FindOps
and the other viaMatchOps
. It could have been easily done so thatmatch
would callfind
and just returnisPresent
on the resultingOptional
. I just know I will not be able to sleep normally until I understand why...