Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to check if all elements match a condition

Short answer

allMatch() returns true if the condition holds for every element:

void main() {
    var ages = List.of(21, 34, 19);
 
    IO.println(ages.stream().allMatch(age -> age >= 18));
    IO.println(ages.stream().allMatch(age -> age >= 20));
}

Output:

true
false

At least one and none

anyMatch() checks that at least one element matches, noneMatch() that none do:

void main() {
    var passwords = List.of("secret1", "qwerty", "Tr0ub4dor");
 
    IO.println(passwords.stream().anyMatch(p -> p.length() > 8));
    IO.println(passwords.stream().noneMatch(String::isBlank));
}

Output:

true
true

Stopping at the first answer

These methods stop checking as soon as the answer is known:

void main() {
    boolean result = Stream.of(1, 2, 3, 4)
            .peek(n -> IO.println("checking " + n))
            .allMatch(n -> n < 2);
    IO.println(result);
}

Output:

checking 1
checking 2
false

Common mistake

Forgetting about an empty list. allMatch() returns true for an empty stream, and anyMatch() returns false:

void main() {
    List<Integer> empty = List.of();
 
    IO.println(empty.stream().allMatch(n -> n > 100));
    IO.println(empty.stream().anyMatch(n -> n > 100));
}

Output:

true
false

If an empty list should give false, check !list.isEmpty() separately.

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.