gpt4 book ai didi

java - 如何在 java 中组合多个类型列表(对我来说)或其他类型的 CompletionStage 响应

转载 作者:行者123 更新时间:2023-11-29 04:16:32 25 4
gpt4 key购买 nike

我正在尝试创建多个 CompletionStage 类型的列表,例如。 CompletionStage<List<Car>> .最后我想合并所有 <List<Car>> 类型的回复在一个 CompletionStage 中加入一个列表。

CompletionStage<List<Car>> completionStageOne= carClientOne.getCarList();
CompletionStage<List<Car>> completionStageTwo= carClientTwo.getCarList();
CompletionStage<List<Car>> completionStageThree= carClientThree.getCarList();

所以在这里,假设我有 3 种不同的服务,它们会给我不同的汽车列表,如 CompletionStage<List<Car>> 的响应形式

现在我试图将它们组合起来并创建一个通用的汽车列表,但我遇到了问题。我正在使用下面的代码来合并结果

CompletionStage<List<Car>> completionStageOneTwo = completionStageOne
.thenCombine(completionStageTwo,(x, y) -> Stream.concat(x.stream(), y.stream()).collect(Collectors.toList()));

//above will work but if I add the third one then it will not.

CompletionStage<List<Car>> completionStageFinal = completionStageOneTwo
.thenCombine(completionStageThree,(x, y) -> Stream.concat(x.stream(), y.stream()).collect(Collectors.toList()));

最后我在做

List<Car> finalList = completionStageFinal.toCompletableFuture().get();

那么我做错了什么?我怎样才能将这三者结合起来?我挡住了什么东西吗?

注意:我已经检查过这个 answer from Holger ,但不知道如何在那里使用 concat。

最佳答案

让我举个例子。我将展示如何使用允许等待所有 future 的 CompletableFuture.AllOf(...)

    // create promises to get cars
CompletableFuture<List<String>> cars1 = CompletableFuture.completedFuture(Arrays.asList("BMW", "Alfa"));
CompletableFuture<List<String>> cars2 = CompletableFuture.completedFuture(Collections.singletonList("WV"));
CompletableFuture<List<String>> cars3 = CompletableFuture.completedFuture(Collections.singletonList("FIAT"));

// collect promises just for convenience
List<CompletableFuture<List<String>>> allFutures = Arrays.asList(cars1, cars2, cars3);

// wait until all cars will be obtained
CompletableFuture<List<String>> listCompletableFuture =
CompletableFuture.allOf(cars1, cars2, cars3)
.thenApply(avoid -> allFutures //start to collect them
.stream()
.flatMap(f -> f.join().stream()) //get List from feature. Here these cars has been obtained, therefore non blocking
.collect(Collectors.toList())
);

// there are here
listCompletableFuture.join().forEach(System.out::println);

输出:

BMW
Alfa
WV
FIAT

关于java - 如何在 java 中组合多个类型列表(对我来说)或其他类型的 CompletionStage 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52048460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com