为什么Streams.allMatch(在Java8中为试图评估所有表达式,即使可以在中间确定值的情况?

问题描述 投票:0回答:1

考虑此摘要-

 String a = "hello" , b = null, c = "guru";
  boolean value = Stream
  .of(a, b, b.substring(2),c)
  .allMatch(x -> x != null);

  System.out.println(value);

这将导致NPE。似乎正在执行b.substring(2),并且由于b为空,因此引发了NPE。为什么要评估这种情况?第二个表达式b为null,因此计算为false。因此,无论后续操作的真值如何,allMatch都将为false。在那种情况下,为什么要尝试评估b.substring(2)?

https://www.geeksforgeeks.org/stream-allmatch-java-examples/https://howtodoinjava.com/java8/stream-allmatch-example/声称,如果不是确定结果所必需的,则可能不评估所有表达式。显然,这里似乎不是这样。

Java 7之前-

if(b != null && b.substring(2) != null)

这不会引发NPE,因为b!= null为false,它本身将返回false。因此,我们可以说Streams.allMatch与上述Java代码段不完全相同吗?


java java-8 stream
1个回答
0
投票

写作时

Stream.of(a, b, b.substring(2),c)

应该准备流的后备数据结构。那将需要知道要存储的值是什么。在评估b.substring时,显然会因NPE而失败。意思是,它根本不应该达到allMatch

© www.soinside.com 2019 - 2024. All rights reserved.