Optional.ofNullable and method chaining

后端 未结 3 1891
渐次进展
渐次进展 2020-12-05 04:18

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

private Optional          


        
相关标签:
3条回答
  • 2020-12-05 04:41

    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.

    0 讨论(0)
  • 2020-12-05 04:51

    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.

    0 讨论(0)
  • 2020-12-05 04:53
    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.

    0 讨论(0)
提交回复
热议问题