如果 findFirst() 找到的第一个元素为 null,为什么会抛出 NullPointerException? [英] Why does findFirst() throw a NullPointerException if the first element it finds is null?

查看:40
本文介绍了如果 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() 能够处理 nulls 更有意义.

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 nulls.

更新了 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

这篇关于如果 findFirst() 找到的第一个元素为 null,为什么会抛出 NullPointerException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆