为什么会抛出 java.lang.NullPointerException
?
List<String> strings = new ArrayList<>();
strings.add(null);
strings.add("test");
String firstString = strings.stream()
.findFirst() // Exception thrown here
.orElse("StringWhenListIsEmpty");
//.orElse(null); // Changing the `orElse()` to avoid ambiguity
strings
中的第一项是null
,这是一个完全可以接受的值。此外,findFirst()
返回 Optional ,这让 findFirst()
能够处理 null
更有意义。
编辑:更新了 orElse()
以减少歧义。
最佳答案
原因是使用了Optional<T>
在返回。 Optional 不允许包含 null
.从本质上讲,它无法区分“它不存在”和“它存在,但它被设置为 null
”的情况。
这就是为什么 the documentation明确禁止 null
时的情况在 findFirst()
中选择:
Throws:
NullPointerException
- if the element selected isnull
关于java - 如果 findFirst() 找到的第一个元素为 null,为什么会抛出 NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32466799/