Optional.ofNullable and method chaining

sebast26 picture sebast26 · Feb 11, 2016 · Viewed 23.4k times · Source

I was surprised by Optional.ofNullable method. Some day I wrote a function that supposed to return an Optional:

private Optional<Integer> extractFirstValueFrom(InsightsResponse insight) {
    return Optional.ofNullable(insight.getValues().get(0).getValue());
}

I mistakenly thought that Optional.ofNullable will prevent any NullPointerExceptions inside of argument expression.

Now I think I know that it was very foolish idea. Java have to resolve arguments first to pass it to Optional.ofNullable invocation.

But I have a question. Is there a nice and good way to accomplish my goal? I would like to obtain from expression insight.getValues().get(0).getValue() some Integer value or null. Null can be each one of the expressions: insight.getValues() or insight.getValues().get(0).

I know that I can just put this in try/catch block but I am wondering if there is more elegant solution.

Answer

Tunaki picture Tunaki · Feb 11, 2016

If you have no idea what can be null, or want to check everything for null, the only way is to chain calls to Optional.map:

If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.

As such, if the mapper return null, an empty Optional will be returned, which allows to chain calls.

Optional.ofNullable(insight)
        .map(i -> i.getValues())
        .map(values -> values.get(0))
        .map(v -> v.getValue())
        .orElse(0);

The final call to orElse(0) allows to return the default value 0 if any mapper returned null.