如何从CompletableFuture中获取不同可选类型的对象



我有一个代码片段,它基于if条件调用两个不同的服务。并且这两个服务都返回CCD_ 2。下面的代码逻辑看起来像

if(someCondition){
CompletableFuture<Optional<SomeObjectType1>> = service1.call();
}else{
CompletableFuture<Optional<SomeObjectType2>> = service2.call();
}

而且SomeObjectType1SomeObjectType2里面都有一个String,这是我感兴趣的。我当前的代码如下:

private ContentWrapper getContentWrapper(input1, input2, ....) {
String content = null;
if (some_condition is true) {
List<Object_Type_1> list = service1.fetchTheCompletableFuture(..... inputs...)
.join()
.map(ListOutput::getList)
.orElse(null);
if (CollectionUtils.isNotEmpty(list)) {
content = list.get(0).getContent();
}
} else {
content = service2
.fetchTheCompletableFuture(..... inputs...)
.join()
.map(RenderedContent::getContent)
.orElse(null);
}
return content != null ? new ContentWrapper(content) : null;
}

现在我的问题是,这个if-else子句是否可以删除,或者通过使用lambdas使其更加清晰。我是lambdas的新手,对此没有很好的想法。

我不确定下面的代码是否因为模糊而编译。

private ContentWrapper getContentWrapper(input1, input2, ....) {
Optional<RenderedContent> content = some_condition
? service1
.fetchTheCompletableFuture(..... inputs...)
.join()
.map(ListOutput::getList)
.stream()
.findFirst()
: service2
.fetchTheCompletableFuture(..... inputs...)
.join();
}
return content
.map(RenderedContent::getContent)
.map(ContentWrapper::new).orElse(null);
}
  • 第一个服务似乎产生了一个RenderedContext列表,如果有,则取其第一个
  • 第二服务可以立即产生呈现的内容

因此,您可以将if-else加入Optional<RenderedContent>。如果map(RenderedContent::getContent)一开始是空的,那么它将产生Optional.empty()。否则CCD_ 10被调用并被封装在CCD_ 11中。如果存在,则可能调用CCD_ 12。

注意很多可能会失败,比如getContent返回null(尽管有一个Optional.ofNullable.

尽管如此,Streams可能非常有表现力。

我会避免使用null来支持Optional,因为它在一起效果更好。

最新更新