当以相同的顺序应用于相同的一系列条件时,||
和 在Stream.of(..).anyMatch(e-> e==true)
功能上是否相同?
任务:对一系列条件运行快速测试以确定是否有任何条件为真。
可能的解决方案: - 用“或”符号 ( ||
)分隔每个条件 - 将每个条件包含在Stream.of(..)
附加的语句中.anyMatch(e-> e==true)
anyMatch(..)
状态文档“返回此流的任何元素是否与提供的谓词匹配。如果不是确定结果所必需的,则不得评估所有元素的谓词[强调]。”
基于这种说法,我的理解是,上面指出的两个解决方案在功能上是相同的,因此如果 4 组中的第二个元素是第一个元素 ,则true
不会评估元素 3 和 4。
然而,在实践中,这似乎不是真的。考虑以下 where item
is null
、empty
istrue
和UtilMethods.isEmpty(..)
is 是一个自定义库方法,用于测试给定参数是null
还是空String
(""):
@Override
protected void updateItem(Pair<K, V> item, boolean empty) {
super.updateItem(item, empty);
boolean test1 = empty
|| Objects.isNull(item)
|| UtilMethods.isEmpty(item.toString())
|| Objects.isNull(item.getValue());
boolean test2 = Stream.of(
empty,
isNull(item),
UtilMethods.isEmpty(item.toString()),
isNull(item.getValue()))
.anyMatch(e -> e == true);
}
Run Code Online (Sandbox Code Playgroud)
该||
代码运行正常。但是,当到达第三个元素时Stream.of(..).anyMatch(..)
抛出 aNullPointerException
因为item
is null
。
鉴于anyMatch(..)
上面引用的文档,这没有意义,这表明甚至不应该达到第三个元素。还是我在这里遗漏了什么?
谢谢
UtilMethods.isEmpty(item.toString())
在Stream.of()
执行之前进行评估,因此NullPointerException
无论您是否在anyMatch
之后调用,它都会抛出 a 。
Stream.of()
,就像任何方法调用一样,在执行之前评估其所有参数,因此它必须评估UtilMethods.isEmpty(item.toString())
。
您可以在更简单的代码段中看到相同的行为:
String s = null;
Stream<Integer> stream = Stream.of (5,s.length());
Run Code Online (Sandbox Code Playgroud)
因此, 的文档anyMatch
与您观察到的行为无关。
归档时间: |
|
查看次数: |
155 次 |
最近记录: |