Why does Stream.allMatch() return true for an empty stream?

后端 未结 5 1684
难免孤独
难免孤独 2020-11-30 07:16

My colleague and I had a bug that was due to our assumption that an empty stream calling allMatch() would return false.

if (myItem         


        
5条回答
  •  既然无缘
    2020-11-30 07:57

    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.

提交回复
热议问题