Search code examples
javajava-8java-stream

Java Streams: find if stream contains null


Most probably a duplicate, however I was not able to find any particular one.

Given

public static void main(String[] args) {
    System.out.println(
            Arrays.asList(null, null, 1)
                    .stream()
                    .filter(obj -> obj == null)
                    .findAny()
                    .isPresent()
    );
}

Expectation

Should at least work (i.e return false because findAny returns Optional).

Actual

NullPointerException is thrown

Question

Is it a bug or a feature?

Thanks for your opinion and explanation.


Solution

  • This behavior is highlighted in the Javadoc for findAny() https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#findAny--

    Returns:an Optional describing some element of this stream, or an empty Optional if the stream is empty

    Throws:NullPointerException - if the element selected is null

    Since you are filtering so the Stream only contains nulls, you are getting a NullPointerException as expected.