0

The following code gives me a NullPointerException. As my examine, it is caused by containerModels being null.

 List<DoseDetailMutableDTOToBaseDoseDetailAdapter> adapters = 
     containerModels.stream()
                    .map(DoseDetailMutableDTOToBaseDoseDetailAdapter::new)
                    .collect(Collectors.toList());

How to fix it using java 8?

ETO
  • 6,970
  • 1
  • 20
  • 37
uma
  • 1,477
  • 3
  • 32
  • 63
  • 1
    `Stream.ofNullable` might help there. – Naman Jan 16 '19 at 08:02
  • @nullpointer is it correct , put it like this, ' containerModels.stream().filter(Objects::nonNull).map..' – uma Jan 16 '19 at 08:04
  • 1
    If `containerModels`, you would still get an NPE. – Naman Jan 16 '19 at 08:06
  • Try like `Optional.ofNullable(lcontainerModels)` – soorapadman Jan 16 '19 at 08:06
  • 1
    @nullpointer `Stream.ofNullable` Java9 right ? – soorapadman Jan 16 '19 at 08:09
  • @nullpointer i am using java 8 . :( – uma Jan 16 '19 at 08:10
  • 1
    @uma check this link this is what you need https://stackoverflow.com/questions/29406286/how-to-best-create-a-java-8-stream-from-a-nullable-object – soorapadman Jan 16 '19 at 08:13
  • 2
    @nullpointer `Optional::ofNullable`, not stream... – Eugene Jan 16 '19 at 08:28
  • 1
    Just `adapters = containerModels == null? Collections.emptyList(): containerModels.stream() .map(DoseDetailMutableDTOToBaseDoseDetailAdapter::new) .collect(Collectors.toList());` or better, fix the preceding code which allowed `containerModels` to ever become `null`. – Holger Jan 16 '19 at 10:36
  • 1
    @Eugene Well when I made the comment I actually meant [`Stream.ofNullable`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/stream/Stream.html#ofNullable(T)).. but of course `Optional.ofNullable` is also an option. – Naman Jan 16 '19 at 11:24
  • 1
    @manfromnowhere yes Java-9. – Naman Jan 16 '19 at 11:26
  • @Holger I too stumble often into the fanciness of the streams/optional to perform such operations and then realize it was better done without them. – Naman Jan 16 '19 at 11:41

1 Answers1

1

This could do the trick:

Optional.ofNullable(containerModels)
        .orElse(Collections.emptyList())
        .stream()
        ...
ETO
  • 6,970
  • 1
  • 20
  • 37