My colleague and I had a bug that was due to our assumption that an empty stream calling allMatch()
would return false
.
if (myItem
When I call list.allMatch
(or its analogs in other languages), I want to detect if any items in list
fail to match the predicate. If there are no items, none might fail to match. My following logic would pick items and expect them to have matched the predicate. For an empty list, I'll pick no items and the logic will still be sound.
What if allMatch
returned false
for an empty list?
My straightforward logic would fail:
if (!myList.allMatch(predicate)) {
throw new InvalidDataException("Some of the items failed to match!");
}
for (Item item : myList) { ... }
I'll need to remember to replace the check with !myList.empty() && !myList.allMatch()
.
In short, allMatch
returning true
for an empty list is not only logically sound, it also lies on the happy path of execution, requiring fewer checks.