gpt4 book ai didi

java - 在 Java 8/11 中是否可以组合 2 个以上的 CompletableFuture?

转载 作者:行者123 更新时间:2023-12-02 09:24:00 27 4
gpt4 key购买 nike

我正在审查来自 CompletableFuture 的运算符 .thenCombine,但是当我尝试组合 2 个以上的 CompletableFuture 对象时,我遇到了一些问题。

示例:

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));

当我尝试添加第三个 CompletableFuture 时,我在 IntelliJ 中收到错误。

有任何反馈吗?

提前非常感谢

胡安·安东尼奥

最佳答案

你可以这样做:

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

您还可以将其封装在单独的函数中:

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));
}

其中 TriFunction 是:

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

并以这种方式使用它:

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

关于java - 在 Java 8/11 中是否可以组合 2 个以上的 CompletableFuture?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58474378/

27 4 0