Why is CompletableFuture.allOf declared as CompletableFuture <Void>?

Why is CompletableFuture.allOf declared as CompletableFuture<Void> and does not return a collection of results or anything else? I think it would be nice to do CompletableFuture.anyOf return CompletableFuture<Object> , but I see that these two methods are related, and therefore I am confused by what they return.

+6
source share
1 answer

anyOf should somehow tell you what was the result of a particular CompletableFuture whose completion was caused by anyOf . This is not necessary in the case of allOf , because you know which futures are completed - all of them.

allOf (just like anyOf ) does not require all futures to be of the same type. Therefore, if he were to return the future of the collection, it would be an Object collection, which is probably not the way you want it.

If you really want allOf return the future of the collection, it's pretty simple to write your own:

 public static CompletableFuture<List<Object>> myAllOf(CompletableFuture<?>... futures) { return CompletableFuture.allOf(futures) .thenApply(x -> Arrays.stream(futures) .map(f -> (Object) f.join()) .collect(toList()) ); } 

If you have a safe version of this problem and need to convert a collection of futures of a certain type into the future of a collection of the same type, see this question for a few examples: List <future> to the future <List> Sequence

+5
source

All Articles