是否可以在 Java 8/11 中组合 2 个以上的 CompletableFuture?
Is it possible to combine more than 2 CompletableFuture in Java 8/11?
我正在审查来自 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));
我正在审查来自 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));