如果你想链接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,或者如果不存在则返回类似 new 的
内容ArrayList<ResultParameterClass>()?
是的,您只需要使用orElseGet(Supplier<? extends T> other)ororElse(T other)提供一个默认值,结果将不再是 aOptional而是 a List<ResultParameterClass>。
所以代码将是:
List<ResultParameterClass> parameters = Optional.ofNullable(response)
...
.map(ProductInstanceClass::getResultParameters)
.orElseGet(ArrayList::new);