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

后端 未结 5 1686
难免孤独
难免孤独 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:39

    Here's another way to think about this:

    allMatch() is to && what sum() is to +

    Consider the following logical statements:

    IntStream.of(1, 2).sum() + 3 == IntStream.of(1, 2, 3).sum()
    IntStream.of(1).sum() + 2 == IntStream.of(1, 2).sum()
    

    This makes sense because sum() is just a generalization of +. However, what happens when you remove one more element?

    IntStream.of().sum() + 1 == IntStream.of(1).sum()
    

    We can see that it makes sense to define IntStream.of().sum(), or the sum of an empty sequence of numbers, in a particular way. This gives us the "identity element" of summation, or the value that, when added to something, has no effect (0).

    We can apply the same logic to Boolean algebra.

    Stream.of(true, true).allMatch(it -> it) == Stream.of(true).allMatch(it -> it) && true
    

    More generically:

    stream.concat(Stream.of(thing)).allMatch(it -> it) == stream.allMatch(it -> it) && thing
    

    If stream = Stream.of() then this rule still needs to apply. We can use the "identity element" of && to solve this. true && thing == thing, so Stream.of().allMatch(it -> it) == true.

提交回复
热议问题