加入后在 CompletableFuture 中返回一个列表
returning a list in CompletableFuture after joining
我有这段代码:
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).collect(Collectors.toList());
我想return一个List,但是return在一个list中的一个list
如果你想按顺序连接两个列表,你可以flatMap
将它们放入流中:
List<PendingWorkflowReturn> combined = Stream.of(cf1,cf2)
.map(CompletableFuture::join)
.flatMap(List::stream) // this replaces each list with the elements of the list in the stream
.collect(Collectors.toList());
或者,您可以使用自定义收集器:
List<PendingWorkflowReturn> combined = Stream.of(cf1,cf2)
.map(CompletableFuture::join)
.collect(ArrayList::new, ArrayList::addAll, ArrayList::addAll);
我有这段代码:
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).collect(Collectors.toList());
我想return一个List,但是return在一个list中的一个list
如果你想按顺序连接两个列表,你可以flatMap
将它们放入流中:
List<PendingWorkflowReturn> combined = Stream.of(cf1,cf2)
.map(CompletableFuture::join)
.flatMap(List::stream) // this replaces each list with the elements of the list in the stream
.collect(Collectors.toList());
或者,您可以使用自定义收集器:
List<PendingWorkflowReturn> combined = Stream.of(cf1,cf2)
.map(CompletableFuture::join)
.collect(ArrayList::new, ArrayList::addAll, ArrayList::addAll);