If you want a synchronous result
Getting the result synchronously is easy.
static int countNames(List<CompletableFuture<Name>> names) {
int count = 0;
for (CompletableFuture<Name> futureName: names) {
if (futureName.join().available) { // this is where you'd get exceptions
count++;
}
}
return count;
}
The only problem is that you'll get exceptions propagated to you, and you'll have to wait for every future to complete in order.
If you want an asynchronous result
This method gives you a result that is also a Future
, allowing you to continue a promise-like flow.
static Future<Integer> countNames(List<CompletableFuture<Name>> names) {
CompletableFuture<Integer> tally = CompletableFuture.completedFuture(0);
for (CompletableFuture<Name> futureName: names) {
tally = futureName.thenCombine(tally, (name, count) -> name.available ? count + 1 : count);
}
return tally;
}