How to use completablefuture and Streams together

Viewed 561

I want to work with CompletableFuture and Stream at the same time. Something like transforming a CompletableFuture<Stream<String>> into a CompletableFuture<Stream<Team>>.

I have done something similar from CompletableFuture<String> to CompletableFuture<Integer>.

CompletableFuture<Stream<String>> getMostPopularTeamNames(int maxResults) {
    CompletableFuture<Stream<String>> mostPopularTeamNames;

    WorldCupSocialApi.getMostPopularTeamNames(1, maxResults, teams -> {
        mostPopularTeamNames = CompletableFuture.supplyAsync(() -> teams.stream());
    });

    return mostPopularTeamNames;
}

I am trying to do something like:

CompletableFuture<Stream<Team>> cf = getMostPopularTeamNames(5).thenApply(s -> {
    s.map(name -> new Team(name))
}

But I am not sure if I the s is going to be the String or the Stream, and if I can map it that way...

1 Answers

So, let's dissect the problem into two smaller problems:

  1. Converting a CompletableFuture<T> to CompletableFuture<R>
  2. Converting a Stream<String> into Stream<Team>

The first one can be achieved using thenApply or thenApplyAsync. The second one can be achieved using a standard map operation on a Stream instance.

And now once you try to combine them, think about just like about applying any other transformation of CompletableFuture<String>, and now it should become clear that you can simply do:

CompletableFuture<Stream<Team>> cf = getMostPopularTeamNames(5)
  .thenApply(s -> s.map(name -> new Team(name));

s is a Stream<String> that gets converted into Stream<Team> - there's no magical conversion between these two types

Related