Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
anyOf
has to somehow tell you what was the result of the specific
CompletableFuture
whose completion triggered
anyOf
. That's not necessary in case of
allOf
because you know which futures completed -- all of them.
allOf
(just as
anyOf
) doesn't require that all futures bear the same type. So if it were to return a future of collection, it would have to be a collection of
Object
which is probably not what you want anyway.
If you really want to have
allOf
return a future of collection, it's fairly straightforward 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 type-safe version of this problem and need to convert a collection of futures of a certain type to a future of collection of that same type, see this question for several examples: List<Future> to Future<List> sequence
–
This is similar to Misha's answer, but with a generic type:
public class Futures {
public static <T> CompletableFuture<List<T>> all(List<CompletableFuture<T>> futures) {
CompletableFuture<Void> cfv = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
return cfv.thenApply(future -> {
return futures.stream()
.map(completableFuture -> completableFuture.join())
.collect(Collectors.toList());
That's the method the Java API should provide.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.