问题描述
我无法确定为什么 findAny()
在 filter()
操作之后抛出空指针异常流。在这个特定的测试用例中,过滤器操作应该已经过滤掉了所有内容,没有留下 findAny()
的结果。
I am having trouble figuring why findAny()
throws a null pointer exception after filter()
operation on a stream. In this particular test case, the filter operation should have filtered out everything, leaving no results for 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()
的预期行为是否抛出空指针如果流不包含任何元素,则会出现异常吗?
Is this expected behavior for findAny()
to throw a null pointer exception if the stream doesn't contain any elements?
编辑:解析可能过滤掉所有元素的过滤操作的优雅且实用的方法是什么?
What is an elegant and functional way to resolve filter operations that might filter out all elements?
推荐答案
避免NPE的最佳方法是:
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()))如果n.textValue()为空,code>将不会抛出NPE
这篇关于在filter()操作过滤掉所有内容后,Java流findAny()遇到空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!