Java 8使用Optional避免空指针检查 [英] Java 8 avoiding null pointer checks using Optional

查看:71
本文介绍了Java 8使用Optional避免空指针检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to write something like this and to avoid checking if elements are not null and collections not empty:

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

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

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

Basically, what I want to achieve is to avoid if statement with multiple checking weather object is null or collection is empty in the hierarchy. I read in the post from my above that this is possible with Optional "Null checks are automatically handled under the hood."

如果已经有了一些解决方案,请重复进行此操作,对不起,请转给我.

If there is some solution already, sorry for making duplicate and please refer me to it.

推荐答案

如果要链接 Optional ,则可以使用其

If you want to chain Optional, you can use its map(Function<? super T,? extends U> mapper) method to call the mapper function only if it is not null and use flatMap(Stream::findFirst) to get the first element of your Collection as next:

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>()?

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

是的,您只需要使用

Yes it is, you simply need to use orElseGet(Supplier<? extends T> other) or orElse(T other) to provide a default value, the result won't be an Optional anymore but a List<ResultParameterClass>.

因此,代码应为:

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

这篇关于Java 8使用Optional避免空指针检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆