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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With