是否可以编写这样的内容并避免检查元素是否不为空并且集合是否不为空:
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
,您可以使用它的 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);
<小时/>
Is it possible to return the list if present in
Optional
, or if not present then return something like newArrayList<ResultParameterClass>()
?
是的,您只需使用 orElseGet(Supplier<? extends T> other)
或 orElse(T other)
提供默认值,结果不会是 Optional
不再是 List<ResultParameterClass>
.
所以代码将是:
List<ResultParameterClass> parameters = Optional.ofNullable(response)
...
.map(ProductInstanceClass::getResultParameters)
.orElseGet(ArrayList::new);
关于Java 8 使用Optional 避免空指针检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40468876/