Java Reference ยท Streams and Functional
Java Stream anyMatch(), allMatch() and noneMatch()
Reference for Java Stream anyMatch(), allMatch() and noneMatch(): test a predicate against elements, short-circuit behavior and the empty-stream results.
The three match operations answer yes/no questions about a stream. anyMatch(p) is true if at least one element satisfies the predicate, allMatch(p) is true if every element does, and noneMatch(p) is true if no element does. They are terminal and short-circuiting: they stop reading as soon as the answer is known.
Together they replace the common hand-written loops that set a boolean flag and break.
boolean hasNegative = nums.stream().anyMatch(n -> n < 0); boolean allAdults = people.stream().allMatch(p -> p.age() >= 18);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
boolean anyMatch(Predicate<? super T> predicate) boolean allMatch(Predicate<? super T> predicate) boolean noneMatch(Predicate<? super T> predicate)
| Name | Description |
|---|---|
predicate |
A non-interfering, stateless test applied to elements. |
Returns: a boolean. For an empty stream: anyMatch is false, allMatch is true, noneMatch is true.
Throws: NullPointerException if the predicate is null.
Usage notes
- Short-circuiting:
anyMatchstops at the firsttrue,allMatchat the firstfalse,noneMatchat the firsttrue. Earlier pipeline stages such aspeek()run only for the elements actually examined. - Infinite streams: a match operation terminates on an infinite stream only if it reaches a deciding element.
allMatchon an infinite stream where every element passes never ends. - Empty streams:
allMatchandnoneMatchreturntruefor no elements. Check for emptiness first if that matters, for example withcount(). - Equivalences:
noneMatch(p)equals!anyMatch(p), andallMatch(p)equals!anyMatch(p.negate()). - Getting the element: the match methods return only a boolean. Use
findFirst()withfilter()to obtain the matching element. - Collections: for a simple membership test,
collection.contains(x)is clearer. For removing matches seeremoveIf(). - Parallel streams: results are the same, but which element ends the search is unspecified.
Related
stream-find,stream-filter,fi-predicate- Lessons: Streams, Functional interfaces