Easy java streams

anyMatch versus allMatch versus noneMatch

The 30 second answer

anyMatch asks whether at least one element passes, allMatch whether every element passes, and noneMatch whether no element passes. All three are short-circuiting terminal operations, so they stop as soon as the answer is known, even on an infinite stream. The trap is the empty stream: anyMatch returns false, but allMatch and noneMatch both return true without ever calling the predicate.

Could you say this in an interview?
var values = List.of(12, 7, 64, 3);

boolean anyAbove50 = values.stream().anyMatch(n -> n > 50);   // true
boolean allPositive = values.stream().allMatch(n -> n > 0);   // true
boolean noneNegative = values.stream().noneMatch(n -> n < 0); // true

IntStream.empty().anyMatch(n -> n > 0);  // false
IntStream.empty().allMatch(n -> n > 0);  // true
IntStream.empty().noneMatch(n -> n > 0); // true

IntStream.iterate(1, n -> n + 1).anyMatch(n -> n > 50); // true, stops at 51

Short-circuiting: each one may skip the rest of the stream once the result is decided. anyMatch stops at the first match, and allMatch stops at the first element that fails. That makes them cheaper than filter(...).count() > 0, which has to visit every element.

Empty stream: the Javadoc states that on an empty stream allMatch and noneMatch return true and anyMatch returns false, and the predicate is not evaluated. This is vacuous truth: "all of nothing" holds. Code like "allow the order if all items are in stock" approves an empty order unless you check for empty first.

Relationships: noneMatch(p) equals !anyMatch(p), and allMatch(p) equals noneMatch(p.negate()). !allMatch(p) is not the same as noneMatch(p).

What interviewers listen for: the empty-stream answer, the short-circuiting, and using list.contains(x) instead of anyMatch(e -> e.equals(x)) for plain equality. The predicate should be stateless and should not modify the source.

Sources (2)
  1. Stream.anyMatch, allMatch, noneMatchdocs.oracle.com
  2. java.util.stream package (short-circuiting operations)docs.oracle.com