将 IntStream 中的 CompletableFuture 值添加到最终的 CompletableFuture 变量

Add CompletableFuture values from IntStream to a final CompletableFuture variable

我正在尝试创建一种方法,该方法在 CompletableFuture 变量中计算在 IntStream 中计算的其他 CompletableFuture 的总和。不幸的是,我的值没有添加到我需要的最终变量中,它最终为 0。我的代码如下:

CompletableFuture<Long> finalAmount = CompletableFuture.completedFuture(0L);

IntStream.range(rankUpEvent.getOldClubRank()+1, rankUpEvent.getNewClubRank()).forEach(
    rank -> {
        if (!clubs.containsKey(rank)) {
            finalAmount.thenCompose(startValue -> configService.getConfig(id, rank - 1).
                thenApply(config -> getAmount(config, "value")));
        }
    }
);
return finalAmount; 

我需要在我的 finalAmount 变量中包含在 IntStream 中计算的每个结果的总和。

求和Stream<CompletableFuture<Integer>>的结果:

CompletableFuture<Integer> sum = stream.reduce(
  CompletableFuture.completedFuture(0),
  (f1, f2) -> f1.thenCombine(f2, Integer::sum));

您当前方法的问题是 thenComposethenApply return new futures,没有更新旧的,等等您正在创建期货,然后丢弃其结果。

您需要达到 Stream<CompletableFuture<Integer>> 然后应用该技术。