为什么Stream.allMatch()为空流返回true? [英] Why does Stream.allMatch() return true for an empty stream?

查看:151
本文介绍了为什么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并可能用于如果声明。考虑到这些事实,是否有任何理由为 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?

推荐答案

这被称为空洞的真相。空集合的所有成员都满足你的条件;毕竟,你能指出一个没有的吗?Simila rly, anyMatch 返回false,因为您找不到与该条件匹配的集合元素。这让很多人感到困惑,但事实证明这是为空集定义any和all的最有用和最一致的方法。

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? 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆