Java 8 使用 Optional 避免空指针检查

Java 8 avoiding null pointer checks using Optional

是否可以这样写并避免检查元素是否为空且集合是否为空:

 response.getBody()
    .getRequestInformation()
    .getRequestParameters().get(0)
    .getProductInstances().get(0)
    .getResultParameters()

我找到了这样的东西 http://winterbe.com/posts/2015/03/15/avoid-null-checks-in-java/

基本上,我想要实现的是避免 if 具有多个检查天气对象的语句为 null 或层次结构中的集合为空。我从上面的 post 中读到 Optional "Null checks are automatically handled under the hood."

是可能的

如果已经有一些解决方案,抱歉复制了,请参考。

如果要链Optional,可以用它的map(Function<? super T,? extends U> mapper)方法调用mapper函数,只有不是null,用flatMap(Stream::findFirst)得到Collection 的第一个元素如下:

Optional<List<ResultParameterClass>> parameters = Optional.ofNullable(response)
    .map(ResponseClass::getBody)
    .map(BodyClass::getRequestInformation)
    .map(RequestInformationClass::getRequestParameters)
    .map(Collection::stream)
    .flatMap(Stream::findFirst)
    .map(RequestParameterClass::getProductInstances)
    .map(Collection::stream)
    .flatMap(Stream::findFirst)
    .map(ProductInstanceClass::getResultParameters);

Is it possible to return the list if present in Optional, or if not present then return something like new ArrayList<ResultParameterClass>()?

是的,您只需使用 orElseGet(Supplier<? extends T> other) or orElse(T other) 提供 一个默认值 ,结果将不再是 Optional,而是List<ResultParameterClass>.

所以代码将是:

List<ResultParameterClass> parameters = Optional.ofNullable(response)
    ...
    .map(ProductInstanceClass::getResultParameters)
    .orElseGet(ArrayList::new);