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)?
Java 7之前-
if(b != null && b.substring(2) != null)
这不会引发NPE,因为b!= null为false,它本身将返回false。因此,我们可以说Streams.allMatch与上述Java代码段不完全相同吗?
写作时
Stream.of(a, b, b.substring(2),c)
应该准备流的后备数据结构。那将需要知道要存储的值是什么。在评估b.substring
时,显然会因NPE而失败。意思是,它根本不应该达到allMatch
。