- Amir Boroumand | Software engineer based in Pittsburgh, PA/
- blog/
- Java Streams: Use anyMatch() over count() > 0 for checking at least one occurrence/
Java Streams: Use anyMatch() over count() > 0 for checking at least one occurrence
Overview #
Streams were introduced in Java 8. When working with streams, there are times when we just want to determine if there is at least one occurrence that matches our predicate or criteria.
In this article, I’ll discuss why using the anyMatch(predicate)
method in the Java Stream API is both safer and more performant than using filter(predicate).count > 0
in these situations.
Short Circuiting #
The fundamental difference between anyMatch()
and count()
is that anyMatch()
is short-circuiting which means it will stop at the first match whereas count()
will count all matches before returning.
Depending upon the stream size, this difference could have huge performance implications.
A Stream of 100,000 objects #
Imagine working with a list of 100,000 Employee objects where we want to determine if any employees are inactive:
|
|
Output #
count() > 0
---------------------
Start time: 1583177821492
End time: 1583177821512
anyMatch()
---------------------
Start time: 1583177821512
End time: 1583177821513
As we can see from the sample output, anyMatch is substantially faster (1ms) than count (20ms).
An Infinite Stream #
If we end up creating an infinite stream of elements such as the code below, then the count()
method will never terminate where as the anyMatch()
approach will terminate upon finding the first match.
count #
IntStream infiniteStream = IntStream.iterate(0, i -> i + 2);
// Never terminates
boolean test = stream.filter(i -> i <= 50).count() > 0;
anyMatch #
IntStream infiniteStream = IntStream.iterate(0, i -> i + 2);
// Terminates at first match of i <= 50
boolean test = stream.anyMatch(i -> i <= 50);