今天有位开发同学在群上说,Stream.allMatch 对于空集合,不管判断条件是啥,直接返回 true。
忍不住试了一下,真的是这样哦!
真的是这样再看看文档,其实写的很清楚了:
其实文档里也写的很清楚了的这位同学又说:「我觉得noneMatch跟anyMatch在空的时候返回还是可以理解的,但是allMatch默认返回true就觉得难以理解了...」
我也有一样的困惑!于是打开google,马上从万能Stackoverflow找到了答案,看来还不少人感兴趣:https://stackoverflow.com/questions/30223079/why-does-stream-allmatch-return-true-for-an-empty-stream
高票答案来自user2357112:
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.
我来翻译一下:
这叫做 vacuous truth。空集合里,所有(all)成员都满足判断条件:在里面你确实找不到一个不满足的,对不?同样地,anyMatch 返回 false,因为在里面,你也找不到一个满足条件的。很多人对此感到迷惑,但实际上这是对集合的 "any" 跟 "all" 最有用、最符合逻辑的定义了。
然后点开 vacuous truth 这个维基百科链接,看到第一段话写得很好理解:
In mathematics and logic, a vacuous truth is a statement that asserts that all members of the empty set have a certain property. For example, the statement "all cell phones in the room are turned off" will be true whenever there are no cell phones in the room.
再来翻译一下:
在数学和逻辑学里,vacuous truth 是指一个真命题,他断言空集合里所有成员怎么怎么样。比如说,如果房间里没有手机,命题 “房间里所有手机都关机了” 为真。
这下感觉明白多了。真是适合学习的一天啊!
网友评论