是否可以编写这样的内容并避免检查元素是否不为空并且集合是否不为空:
response.getBody()
.getRequestInformation()
.getRequestParameters().get(0)
.getProductInstances().get(0)
.getResultParameters()
我发现了这样的东西http://winterbe.com/posts/2015/03/15/avoid-null-checks-in-java/
基本上,我想要实现的是避免带有多个检查天气对象的 if 语句为空或层次结构中的集合为空。我在上面的帖子中读到,这可以通过可选的“空检查在幕后自动处理”来实现。
如果已经有一些解决方案,很抱歉重复,请参考。
如果你想连锁Optional
,你可以使用它的map(Function<? super T,? extends U> 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);
如果存在于中,是否可以返回列表Optional
,或者如果不是
呈现然后返回类似新的东西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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)