Why does findFirst() throw a NullPointerException if the first element it finds is null?

neverendingqs picture neverendingqs · Sep 8, 2015 · Viewed 77.4k times · Source

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

EDIT: updated the orElse() to be less ambiguous.

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Sep 8, 2015

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 is null