lambda null指针异常

时间:2018-03-26 16:17:27

标签: lambda collections java-8

我正在尝试按如下方式对集合进行过滤和排序:

List<Tls201Appln> appsFiltered = apps.stream()
                    .filter(x -> x.getTls203ApplnAbstr().getApplnAbstractLg().toLowerCase().equals("en"))
                    .sorted((x1, x2) -> x1.getApplnFilingDate().after(x2.getApplnFilingDate()) ? 1 : x1.getApplnFilingDate().before(x2.getApplnFilingDate())?-1:0)
                    .collect(Collectors.toList());

它抛出以下异常

java.lang.NullPointerException
    at it.jrc.tim.patstat.beans.PatstatExtractorAutumn2015.lambda$0(PatstatExtractorAutumn2015.java:402)
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:174)
    at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
    at it.jrc.tim.patstat.beans.PatstatExtractorAutumn2015.findLastPatentNumber(PatstatExtractorAutumn2015.java:404)

applnFilingDate是Tls201Appln上的非null属性。 空指针来自哪里?

1 个答案:

答案 0 :(得分:0)

空指针异常出现在第二行。 将lambda表达式拆分为多行并处理空指针异常可以解决问题,如下所示:

List<Tls201Appln> appsFiltered = apps.stream()
                    .filter(x -> {
                        if(x!= null && x.getTls203ApplnAbstr() !=null  && x.getTls203ApplnAbstr().getApplnAbstractLg() != null) {

                            return x.getTls203ApplnAbstr().getApplnAbstractLg().toLowerCase().equals("en");
                        }
                        else return false;
                    })
                    .sorted((x1, x2) -> x1.getEarliestFilingDate().after(x2.getEarliestFilingDate()) ? 1 : x1.getEarliestFilingDate().before(x2.getEarliestFilingDate())?-1:0)
                    .collect(Collectors.toList());