Search code examples
javacompletable-future

Add CompletableFuture values from IntStream to a final CompletableFuture variable


I am trying to create a method which calculates in a CompletableFuture variable the sum of other CompletableFutures which are calculated in an IntStream. Unfortunately, my values do not add to the final variable that I need and it ends up as being 0. My code is below:

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; 

I need to have in my finalAmount variable the sum of each result computed in the IntStream.


Solution

  • To sum the results of a Stream<CompletableFuture<Integer>>:

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

    The problem with your current approach is that thenCompose and thenApply return new futures, not updating the old one, and so you're creating futures and then discarding their results.

    You need to get to a Stream<CompletableFuture<Integer>> and then apply that technique.