本文介绍了为什么 Stream.allMatch() 为空流返回 true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我和我的同事有一个错误,这是由于我们假设调用 allMatch() 的空流将返回 false.

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

if (myItems.allMatch(i -> i.isValid()) {
    //do something
}

当然,假设和不阅读文档是我们的错.但是我不明白为什么空流的默认 allMatch() 行为返回 true.这样做的原因是什么?与 anyMatch()(相反地返回 false)一样,这个操作以命令方式使用,它离开 monad 并且可能用在 if 语句中.考虑到这些事实,是否有任何理由让 allMatch() 在空流上默认为 true 对于大多数用途来说是可取的?

Of course, it is kind of our fault for assuming and not reading documentation. But what I don't understand is why the default allMatch() behavior for an empty stream returns true. What was the reasoning for this? Like the anyMatch() (which contrarily returns false), this operation is used in an imperative way that departs the monad and probably used in an if statement. Considering those facts, is there any reason why having allMatch() default to true on an empty stream be desirable for majority of uses?

推荐答案

这被称为 空洞的真相.一个空集合的所有成员都满足你的条件;毕竟,你能指出一个没有吗?

This is known as vacuous truth. All members of an empty collection satisfy your condition; after all, can you point to one that doesn't?

类似地,anyMatch 返回 false,因为您无法在集合中找到与条件匹配的元素.这让很多人感到困惑,但事实证明这是为空集定义任何"和所有"的最有用和最一致的方式.

Similarly, anyMatch returns false, because you can't find an element of your collection that does match the condition. This is confusing to a lot of people, but it turns out to be the most useful and consistent way to define "any" and "all" for empty sets.

这篇关于为什么 Stream.allMatch() 为空流返回 true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!