CompletableFuture调用join返回嵌套列表,如何获取目标一维List?
问题原因
你代码中CompletableFuture::join返回的结果本身就是List<PendingWorkflowReturn>类型,经过map操作后,流的元素类型为List<PendingWorkflowReturn>,直接调用Collectors.toList()收集就会得到嵌套的List<List<PendingWorkflowReturn>>结构。
解决方案
把map操作后追加flatMap操作,将每个异步返回的列表展开为单个元素的流,再统一收集即可得到一维列表,修改后的代码如下:
import java.util.Collection; // 其余原有导入保持不变 List<PendingWorkflowReturn> pendingWorkflowReturns = new ArrayList<>(); CompletableFuture<List<PendingWorkflowReturn>> cf1 = CompletableFuture.supplyAsync(() -> pendingWorkflows(menageReturn.getId(),"a")); CompletableFuture<List<PendingWorkflowReturn>> cf2 = CompletableFuture.supplyAsync(() -> pendingWorkflows(menageReturn.getId(),"b")); List<PendingWorkflowReturn> combined = Stream.of(cf1,cf2) .map(CompletableFuture::join) // 新增flatMap操作把每个列表的元素展开为流 .flatMap(Collection::stream) .collect(Collectors.toList());
内容的提问来源于stack exchange,提问作者Nunyet Calçada
相关产品推荐
相关产品推荐

