Java Streams: find if stream contains null

tkachuko :

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.

GAdams :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=443266&siteId=1