Java 流查找任何() 在 filter() 操作筛选出所有内容后遇到空指针异常
2022-09-03 01:32:46
我无法弄清楚为什么在对流执行操作后会引发空指针异常。在此特定测试用例中,筛选器操作应已筛选出所有内容,而不留下 任何结果。findAny()
filter()
findAny()
Optional<JsonNode> encryption = sseEncryptionList.stream()
.filter(n -> n.textValue().equals("AES256")) //Filters out everything
.findAny(); //Throws null pointer exception
堆栈跟踪:
Exception in thread "main" java.lang.NullPointerException
at example.Main.lambda$main$0(Main.java:41)
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:174)
at java.util.ArrayList$ArrayListSpliterator.tryAdvance(ArrayList.java:1351)
at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:498)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:485)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:152)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.findAny(ReferencePipeline.java:469)
at example.Main.main(Main.java:42)
如果流不包含任何元素,则引发空指针异常的预期行为是否为 ?findAny()
编辑:解决可能过滤掉所有元素的过滤器操作的优雅而实用的方法是什么?