Optional.ofNullable and method chaining

Solution 1:

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.

Solution 2:

smth like this should work

Optional.ofNullable(insight.getValues()).map(vals -> vals.get(0)).map(v -> v.getValue())

well, according to the sample code given, as #extractFirstValueFrom do not contain neither @Nullable nor checks for null like Guava's checkNotNull(), let's assume that insight is always something. thus wrapping Optional.ofNullable(insight.getValues()) into Option would not result with NPE. then call chain of transformations is composed (each results with Optional) that lead to result Optional<Integer> that might be either Some or None.

Solution 3:

public Optional<Integer> extractFirstValueFrom(InsightsResponse insight) {
    AtomicReference<Optional<Integer>> result = new AtomicReference<>(Optional.empty());
    Optional.ofNullable(insight.getValues().get(0)).ifPresent(ele -> result.set(Optional.ofNullable(ele.getValue())));
    return result.get();
}

I think sometiems you could use ifPresent Api as a null-safe operation. the java.util.Optional#map used ifPresent Api similarly.