You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 15:51:03