Java Stream anyMatch (Predicate predicate) is terminal-short-circuiting operation which is used to check if the stream contains any matching element with provided predicate.
1. Stream anyMatch() method
1.1. Syntax
boolean anyMatch(Predicate<? super T> predicate)
Here predicate
a non-interfering, stateless predicate to apply to elements of the stream.
1.2. Description
- It is a short-circuiting terminal operation.
- It returns whether any elements of this stream match the provided predicate.
- May not evaluate the predicate on all elements if not necessary for determining the result. Method returns
true
as soon as first matching element is encountered. - If the stream is empty then
false
is returned and the predicate is not evaluated.
2. Java Stream anyMatch() example
Java example of Stream.anyMatch()
method to check if any stream element match the method argument predicate.
import java.util.stream.Stream; public class Main { public static void main(String[] args) { Stream<String> stream = Stream.of("one", "two", "three", "four"); boolean match = stream.anyMatch(s -> s.contains("four")); System.out.println(match); //true } }
Program output.
true
3. Difference between anyMatch() vs contains()
Theoretically, there is no difference between anyMatch()
and contains() when we want to check if an element exist in a list.
Parallelism might bring an advantage for really large lists, but we should not casually use the Stream.parallel()
every time and there assuming that it may make things faster. In fact, invoking parallel()
may bring down the performance for small streams.
4. Conclusion
Stream.anyMatch() method can be a useful in certain cases where we need to check if there is at least one element in the stream.
The shorter version list.contains()
also does the same thing and can be used instead.
Reference :
Leave a Reply