jabrena
jabrena

Reputation: 1345

Is it possible to combine more than 2 CompletableFuture in Java 8/11?

I am reviewing the operator .thenCombine from CompletableFuture, but I have some issues when I try to combine more than 2 CompletableFuture objects.

Example:

CompletableFuture<List<String>> completableFuture =
        CompletableFuture.supplyAsync(() -> fetch.andThen(log).apply(url1))
        .thenCombine(CompletableFuture.supplyAsync(() -> fetch.andThen(log).apply(url2)),
        //.thenCombine(CompletableFuture.supplyAsync(() -> fetch.andThen(log).apply(url3)),
        (s1, s2) -> List.of(s1,s2));
        //(s1, s2, s3) -> List.of(s1, s2, s3));

When I try to add the third CompletableFuture, I receive an Error in IntelliJ.

Any feedback?

Many thanks in advance

Juan Antonio

Upvotes: 3

Views: 5087

Answers (1)

IlyaMuravjov
IlyaMuravjov

Reputation: 2492

You can do it this way:

future1.thenCombine(future2, Pair::new)
        .thenCombine(future3, (pair, s3) -> List.of(pair.getKey(), pair.getValue(), s3));

You can also encapsulate it in a separate function:

public static <T1, T2, T3, R> CompletableFuture<R> combine3Future(
        CompletableFuture<T1> future1,
        CompletableFuture<T2> future2,
        CompletableFuture<T3> future3,
        TriFunction<T1, T2, T3, R> fn
) {
    return future1.thenCombine(future2, Pair::new)
            .thenCombine(future3, (pair, t3) -> fn.apply(pair.getKey(), pair.getValue(), t3));
}

Where TriFunction is:

@FunctionalInterface
public interface TriFunction<T, T2, T3, R> {
    public R apply(T t, T2 t2, T3 t);
}

And use it this way:

combine3Future(future1, future2, future3, (s1, s2, s3) -> List.of(s1, s2, s3));

Upvotes: 3

Related Questions