Search code examples
javanullpointerexceptionjava-stream

NullPointerException while iterating over stream


The function below iterates over a stream but for certain input it's throwing a NullPointerException:

public List<DesignTimeLibrary> getDTLData(List<Project> projects, String projLibLocation, String estimatePath) {
    List<DesignTimeLibrary> allDTLs = new ArrayList<DesignTimeLibrary>();
    FileProcessor fileProc = new FileProcessor();
    XPathProcessor xProc = new XPathProcessor();
    projects.stream()
            .filter(pJ-> pJ.getDtlNames().size()>0)
            .flatMap(project -> project.getDtlNames().stream()).filter(Objects::nonNull)
            .forEach(dTL -> {
                if(containsName(allDTLs, dTL)) return;
                Logger.info("***** Processing DTL "+dTL+" *****");
                Map<String, Process> dtlProcesses = null;
                List<SharedResource> dtlResources = null;
                List<Schema> dtlSchemas=null;
                List<Adapter> dtlAdapters = null;
                try {
                    Path pP = fileProc.extractProjLib(projLibLocation + File.separator + dTL, projLibLocation + File.separator + "extracted");
                    DesignTimeLibrary dtl = new DesignTimeLibrary(dTL, pP);
                    ...
                    allDTLs.add(dtl);
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            });
    return allDTLs;
}

The output is:

Processing: WCLEClientV002.projlib
Processing: WCLEClientV002.projlib
java.lang.NullPointerException
    at com.tbt.data.ProjectProcessor.lambda$getDTLData$1(ProjectProcessor.java:77)
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:174)
    at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
    at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
    at com.tbt.data.ProjectProcessor.getDTLData(ProjectProcessor.java:79)

Here the .forEach(dTL -> { is line 79. I've tried debugging but couldn't locate the null object.


Solution

  • The NullPointerException is at line 77, which is here pJ-> pJ.getDtlNames().size()>0. If the getDtlNames() returns null then NullPointerException is thrown, so just add an null check to that filter

     .filter(pJ-> Objects.nonNull(pJ.getDtlNames()) && pJ.getDtlNames().size()>0)