Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum a Stream of CompleteableFuture<BigDecimal> conveniently?

I'm looking for a non-blocking way to sum a Stream of CompleteableFuture<BigDecimal>.

I already found topics closely related to this problem, like this. But unfortunately in my case I do have the BigDecimal packed into a CompleteableFuture and therefore I need to wait for completion first. In the end I would like to get another CompleteableFuture which contains the sum of all Futures within the Stream, once it's completed.

EDIT: Actually I did manage to find the following solution:

Stream<CompletableFuture<BigDecimal>> lotOfWork;
CompletableFuture.supplyAsync(() -> lotOfWork.map(CompletableFuture::join)
                                             .reduce(
                                                 BigDecimal.valueOf(0.0), 
                                                 BigDecimal::add
                                              )
);

But since this is not using any of the CompletionStage methods, I'm pretty sure there is an even better way to do this job.

like image 908
Brainsucker92 Avatar asked Apr 25 '19 22:04

Brainsucker92


1 Answers

Here is the solution with the CompletableFuture::thenCombine as suggested by you directly

I would have prefer a solution that does not enforce the reduction order but didn't find it in the javadoc.

CompletableFuture<BigDecimal> result = lotOfWork.reduce((a,b) -> a.thenCombine(b, BigDecimal::add)).orElse(CompletableFuture.completedFuture(BigDecimal.ZERO));
like image 120
Wisthler Avatar answered Sep 28 '22 07:09

Wisthler