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

时间:2016-11-07 15:32:23

标签: java java-8 optional null-check

是否可以编写类似这样的内容并避免检查元素是否为空且集合不为空:

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

我发现了这样的事情 http://winterbe.com/posts/2015/03/15/avoid-null-checks-in-java/

基本上,我想要实现的是避免if多个检查天气对象的语句为null或者层次结构中的集合为空。我从上面的帖子中读到,这可以通过Optional" Null检查在引擎盖下自动处理。"

如果已经有一些解决方案,抱歉复制,请转介我。

1 个答案:

答案 0 :(得分:6)

如果您要链接Optional,只有当null不是flatMap(Stream::findFirst)并使用Collection来获取第一个时,您才可以使用其map(Function<? super T,? extends U> mapper)方法调用映射器函数您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); 的元素作为下一个:

Optional
  

是否可以返回ArrayList<ResultParameterClass>()中存在的列表,如果不存在则返回   礼物然后返回新的东西   Optional

是的,您只需使用orElseGet(Supplier<? extends T> other)orElse(T other)提供默认值,结果将不再是List<ResultParameterClass>但是List<ResultParameterClass> parameters = Optional.ofNullable(response) ... .map(ProductInstanceClass::getResultParameters) .orElseGet(ArrayList::new);

那么代码就是:

h   ell##!omynam493eisj2ohn