Learnitweb

Check if All Elements Match a Condition

Approach 1: Using allMatch()

List<Integer> nums = Arrays.asList(2,4,6);
boolean allEven = nums.stream().allMatch(n -> n % 2 == 0);
System.out.println(allEven); // true

Why it works:

  • allMatch() checks every element with short-circuiting if any fail.

Approach 2: Using anyMatch() Negation (Alternative)

boolean allEven = !nums.stream().anyMatch(n -> n % 2 != 0);
System.out.println(allEven); // true

Why it works:

  • Logically equivalent to allMatch.