Learnitweb

Check if Any Element Matches a Condition

Approach 1: Using anyMatch()

List<Integer> nums = Arrays.asList(1,3,5,8);
boolean hasEven = nums.stream().anyMatch(n -> n % 2 == 0);
System.out.println(hasEven); // true

Why it works:

  • anyMatch() short-circuits as soon as a match is found.

Approach 2: Using filter() and findAny() (Alternative)

boolean hasEven = nums.stream()
                      .filter(n -> n % 2 == 0)
                      .findAny()
                      .isPresent();
System.out.println(hasEven); // true

Why it works:

  • Equivalent, but less efficient because it creates a filtered stream first.