Java .stream()。findAny()抛出NullpointerException

时间:2018-04-19 14:20:28

标签: java-8 java-stream

我的目标是检查集合中是否存在具有特定ID的对象:

Optional<PolicyCoHolder> policyHolder = policyCoHolderCollection.getPolicyCoHolder()
    .stream()
    .filter(coHolder -> coHolder.getPolicyCoHolderId().longValue() == representativeId)
    .findAny();

我的收藏:

policyCoHolder = {ArrayList@17539}  size = 3
 0 = {PolicyCoHolder@17541} 
 1 = {PolicyCoHolder@17542} 
 2 = {PolicyCoHolder@17543} 

代表性:

representativeId = null

正如文档中所述:

  

返回:描述此流的某个元素的可选项,或者   empty如果流为空,则为可选

     

抛出:NullPointerException - 如果选择的元素为null

但是在我的收藏中没有空元素, .filter()应该过滤掉所有元素,为什么 NPE 会被抛出?

java.lang.NullPointerException: null
    at gold.core.domain.mtpl.mapper.MTPLMapper.lambda$addPolicyCoHolder$1(MTPLMapper.java:303)
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:174)
    at java.util.ArrayList$ArrayListSpliterator.tryAdvance(ArrayList.java:1359)
    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)

1 个答案:

答案 0 :(得分:2)

看来coHolder nullcoHolder.getPolicyCoHolderId()返回null。尝试在原始过滤器之前添加其他filters

Optional<PolicyCoHolder> policyHolder = policyCoHolderCollection.getPolicyCoHolder()
    .stream()
    // will filter out all nulls in the stream
    .filter(Objects::nonNull) 
    // compare values finally, Object::equals can handle null checks properly
    .filter(coHolder -> Objects.equals(coHolder.getPolicyCoHolderId(),representativeId))
.findAny();

当然我们可以将所有3个滤镜合并为1,但在我看来它看起来不太可读。