anyMatch, allMatch and noneMatch
Ask a yes or no question about a stream and stop reading the moment the answer is known.
Open this lesson in the learning hubKey points
- All three take a Predicate and return a plain
boolean. They are terminal ops, so the pipeline runs. anyMatchstops at the first true.allMatchandnoneMatchstop at the first counter-example.- On an empty stream
allMatchis true andanyMatchis false. That is vacuous truth, not a bug. noneMatch(p)always agrees withallMatch(p.negate()). Pick whichever one reads like the sentence in the ticket.- Want the element itself, not a yes or no? Use
filter(...).findFirst()instead.
Example
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> nums = List.of(3, 8, 5, 12, 7);
System.out.println("anyMatch > 10 : " + nums.stream().anyMatch(n -> n > 10));
System.out.println("allMatch odd : " + nums.stream().allMatch(n -> n % 2 == 1));
System.out.println("noneMatch < 0 : " + nums.stream().noneMatch(n -> n < 0));
// Short-circuit proof: anyMatch stops at the first true.
System.out.println("-- anyMatch walk --");
boolean hit = nums.stream()
.peek(n -> System.out.println(" testing " + n))
.anyMatch(n -> n > 4);
System.out.println("found : " + hit + " (12 and 7 were never tested)");
// Empty stream: allMatch is true, anyMatch is false. That is vacuous truth.
List<Integer> empty = List.of();
System.out.println("empty allMatch : " + empty.stream().allMatch(n -> n > 100));
System.out.println("empty anyMatch : " + empty.stream().anyMatch(n -> n > 100));
// noneMatch(p) is the same answer as allMatch(negated p).
System.out.println("agree : "
+ (nums.stream().noneMatch(n -> n > 20) == nums.stream().allMatch(n -> n <= 20)));
}
}
The match family answers the question and then stops reading.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Streams course, and every lesson in it is listed on the Streams contents page.