1

I'm looking for a wall to implement a Collector of CompletableFuture.

I mean, my current code is:

private CompletableFuture<List<BundleEntryResponseComponent>> makeAllOfCompletableFuture(List<CompletableFuture<BundleEntryResponseComponent>> completableFutures) {
    CompletableFuture<Void> allFutures = CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[completableFutures.size()]));

    CompletableFuture<List<BundleEntryResponseComponent>> allCompletableFuture = allFutures.thenApply(future -> {
        return completableFutures.stream()
            .map(completableFuture -> completableFuture.join())
            .collect(Collectors.toList());
        }
    );

    CompletableFuture<List<BundleEntryResponseComponent>> completableFuture = allCompletableFuture.toCompletableFuture();

    return completableFuture;
}

As you can see, I'm joining all CompletableFuture of completableFutures parameter.

I'd like to handle them as a stream of CompletableFuture and join them into a custom Collector.

Something like this:

Stream<CompletableFuture<BundleEntryResponseComponent>> futures ...
CompletableFuture<List<BundleEntryResponseComponent>> allOfFuture = futures
 ...
 .collect(???¿¿¿);

Any ideas?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Jordi
  • 20,868
  • 39
  • 149
  • 333
  • 1
    This does not sound like a typical `stream` operation. If I understand you correctly, you want to start with a stream, and end with one single entity (containing all information from said stream). In this case, it sounds more like you want to transform the `Future`s to their actual result-type (can be done through a stream), create a list of those results (can be done through a stream) and then wrap it in a `Future` (cannot (easily) be done through a stream). – Turing85 Dec 27 '21 at 13:42
  • What about just removing all the redundancy in your current code, e.g. just `return allFutures.thenApply(...`? – Kayaman Dec 27 '21 at 13:50
  • 1
    See [here](https://jensonjava.wordpress.com/2017/11/16/convert-listcompletablefuture-to-completablefuturelist/) – Kayaman Dec 27 '21 at 14:09
  • Exactly, @Kayaman – Jordi Dec 27 '21 at 14:15
  • Apart from the redundancy, what you are doing is the right way to do it. I would just replace the `completableFutures.size()` with just `0` as the former is useless and [even counter-productive](https://stackoverflow.com/a/29444594/525036). – Didier L Dec 28 '21 at 15:36
  • 1
    _"I'm looking for a wall"_ You're looking for a what? – Mark Rotteveel Dec 30 '21 at 12:14
  • @MarkRotteveel I guess it should read “_for a way_” but since you didn’t fix it in your edit I’m wondering if it could mean anything else? – Didier L Jan 03 '22 at 11:00

0 Answers0