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

Ale*_*dar 2 java optional java-8 null-check

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

 response.getBody()
    .getRequestInformation()
    .getRequestParameters().get(0)
    .getProductInstances().get(0)
    .getResultParameters()
Run Code Online (Sandbox Code Playgroud)

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

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

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

Nic*_*tto 6

如果你想链接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);
Run Code Online (Sandbox Code Playgroud)

是否可以返回列表(如果存在)Optional,或者如果不存在则返回新的 ArrayList<ResultParameterClass>()

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

那么代码就是:

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