如果 findFirst() 找到的第一个元素为 null,为什么会抛出 NullPointerException?
为什么会抛出 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()
返回一个 可选,这让 findFirst()
能够处理 null
s 更有意义.
The first item in strings
is null
, which is a perfectly acceptable value. Furthermore, findFirst()
returns an Optional, which makes even more sense for findFirst()
to be able to handle null
s.
更新了 orElse()
以减少歧义.
updated the orElse()
to be less ambiguous.
推荐答案
之所以会这样,是因为在返回中使用了Optional
.Optional 不允许包含 null
.从本质上讲,它没有提供区分它不存在"的情况的方法.并且它在那里,但它被设置为 null
".
The reason for this is the use of Optional<T>
in the return. Optional is not allowed to contain null
. Essentially, it offers no way of distinguishing situations "it's not there" and "it's there, but it is set to null
".
这就是为什么文档明确禁止在findFirst()
中选择null
的情况:
That's why the documentation explicitly prohibits the situation when null
is selected in findFirst()
:
投掷:
NullPointerException
- 如果选择的元素是 null
NullPointerException
- if the element selected is null
相关文章