Java streams findAny() encounters null pointer exception after filter() operation filters out everything

后端 未结 3 2072
时光说笑
时光说笑 2021-02-20 18:41

I am having trouble figuring why findAny() throws a null pointer exception after filter() operation on a stream. In this particular test case, the filt

相关标签:
3条回答
  • 2021-02-20 19:11

    No, it's not the behavior, when the stream doesn't contain any elements. In which case it instead returns an Optional.empty().

    Also, the NPE is the cause of a null value in the stream, as stated in the javadocs:

    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
    
    0 讨论(0)
  • 2021-02-20 19:15

    Your confusion comes from the fact that you filter first - and you would expect the filter method to be somewhere in the stack trace; but notice that intermediate operations do nothing per-se, they are executed lazily and only kick in when a terminal operation is present (such as findAny in your case). It's actually there in the stack trace (the filter method), but it looks like this: Example.Main.lambda$main$0(Main.java:41).

    If you want to filter null values, first do:

    .filter(Objects::nonNull)
    .filter(n -> n.textValue().equals("AES256"))
    .findAny()
    
    0 讨论(0)
  • 2021-02-20 19:20

    The best way to avoid NPE is:

    Optional<JsonNode> encryption = sseEncryptionList.stream()
                  .filter(Objects::nonNull)
                  .filter(n -> "AES256".equals(n.textValue()))
                  .findAny();
    

    "AES256".equals(n.textValue())) will not throw NPE if n.textValue() is null

    0 讨论(0)
提交回复
热议问题