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

后端 未结 3 2084
时光说笑
时光说笑 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:20

    The best way to avoid NPE is:

    Optional 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

提交回复
热议问题