Video in progress

What do anyMatch, allMatch and noneMatch return on an empty stream?

On an empty stream anyMatch returns false, allMatch returns true and noneMatch returns true. Logically: "does any element match the condition?" no; "do all of them match?" there is no element that refutes it, so yes.

📖 Answer

List<Integer> empty = List.of();

empty.stream().anyMatch(x -> x > 0);   // false
empty.stream().allMatch(x -> x > 0);   // true
empty.stream().noneMatch(x -> x > 0);  // true

allMatch returning true surprises many people and becomes a bug in prod:

// "are all payments confirmed?"
boolean allPaid = order.payments().stream().allMatch(Payment::confirmed);
if (allPaid) ship(order);   // ships even if there are no payments at all!

The right way is to check for emptiness separately:

boolean ready = !order.payments().isEmpty()
        && order.payments().stream().allMatch(Payment::confirmed);

All three methods short-circuit: they stop as soon as the answer is known. anyMatch ends at the first matching element, allMatch at the first non-matching one, and the remaining elements aren't checked.