Learnitweb

Check if No Elements Match a Condition

Approach 1: Using noneMatch()

List<String> words = Arrays.asList("cat","dog");
boolean noneLongerThan5 = words.stream().noneMatch(s -> s.length() > 5);
System.out.println(noneLongerThan5); // true

Why it works:

  • noneMatch() is the negation of anyMatch.

Approach 2: Using allMatch() (Alternative)

boolean noneLongerThan5 = words.stream().allMatch(s -> s.length() <= 5);
System.out.println(noneLongerThan5); // true

Why it works:

  • Equivalent using allMatch for a complementary condition.