JaJ JaJ - 6 months ago 17
Java Question

How can I write safe java.util.Optional null pointer assignment when getting aList.get(0)?

I have the following code that throws when my call to .getList().get(0) is null.

Optional<MyObject> _obj = java.util.Optional.ofNullable(objParam);

// where getListOfMyObjects() returns List<MyObjects>
Optional<String> desc = Optional.ofNullable(_obj.get().getMyParentObject().getListOfMyObjects().get(0).getDesc());


How can I write safe java 8 Optional code (use .map, etc,.) that will prevent .getList().get(0) from throwing?

Answer

Is this what you are trying to do?

Optional<String> desc = Optional.ofNullable(objParam)
        .map(MyObject::getMyParentObject)
        .map(MyObject::getListOfMyObjects)
        .filter(lst -> ! lst.isEmpty())
        .map(lst -> lst.get(0))
        .map(MyObject::getDesc);

Another way to do it is by getting the list's stream and then using findFirst. I am not sure if using streams inside optional is very clear, but here's how you would do it:

Optional<String> desc = Optional.ofNullable(objParam)
        .map(MyObject::getMyParentObject)
        .map(MyObject::getListOfMyObjects)
        .map(List::stream)
        .flatMap(Stream::findFirst)
        .map(MyObject::getDesc);
Comments