Why does this throw a 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
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.
EDIT: updated the orElse()
to be less ambiguous.
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
".
That's why the documentation explicitly prohibits the situation when null
is selected in findFirst()
:
Throws:
NullPointerException
- if the element selected isnull