Skip to content
Tutorials Center
My learning

Topics

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.

Java
boolean hasNegative = nums.stream().anyMatch(n -> n < 0);
boolean allAdults   = people.stream().allMatch(p -> p.age() >= 18);

Try it

Java The three questions

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.

Java Short-circuiting and empty streams

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

Java
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: anyMatch stops at the first true, allMatch at the first false, noneMatch at the first true. Earlier pipeline stages such as peek() run only for the elements actually examined.
  • Infinite streams: a match operation terminates on an infinite stream only if it reaches a deciding element. allMatch on an infinite stream where every element passes never ends.
  • Empty streams: allMatch and noneMatch return true for no elements. Check for emptiness first if that matters, for example with count().
  • Equivalences: noneMatch(p) equals !anyMatch(p), and allMatch(p) equals !anyMatch(p.negate()).
  • Getting the element: the match methods return only a boolean. Use findFirst() with filter() to obtain the matching element.
  • Collections: for a simple membership test, collection.contains(x) is clearer. For removing matches see removeIf().
  • Parallel streams: results are the same, but which element ends the search is unspecified.