Last active
November 9, 2022 07:30
-
-
Save jklingsporn/9216cb6e71ff72ec3c20ff3ccfd50675 to your computer and use it in GitHub Desktop.
Converts a Stream<CompletableFuture<X>> to a CompletableFuture<List<X>> or a Stream<CompletableFuture<Void>> to a CompletableFuture<Void>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.List; | |
import java.util.concurrent.CompletableFuture; | |
import java.util.function.Function; | |
import java.util.stream.Collector; | |
import java.util.stream.Collectors; | |
public class CompletableFutureCollector2 { | |
private CompletableFutureCollector2(){ | |
} | |
/** | |
* Transforms a <pre>{@code List<CompletableFuture<T>>}</pre> into a <pre>{@code CompletableFuture<List<T>>}</pre> | |
* @param <X> the computed result type | |
* @param <T> some CompletableFuture | |
* @return a CompletableFuture of <pre>{@code CompletableFuture<List<T>>}</pre> that is complete when all collected CompletableFutures are complete. | |
*/ | |
public static <X, T extends CompletableFuture<X>> Collector<T, ?, CompletableFuture<List<X>>> collectResult(){ | |
return Collectors.collectingAndThen(Collectors.toList(), joinResult()); | |
} | |
/** | |
* Transforms a <pre>{@code List<CompletableFuture<?>>}</pre> into a <pre>{@code CompletableFuture<Void>}</pre> | |
* Use this function if you are not interested in the collected results or the collected CompletableFutures are of | |
* type Void. | |
* @param <T> some CompletableFuture | |
* @return a <pre>{@code CompletableFuture<Void>}</pre> that is complete when all collected CompletableFutures are complete. | |
*/ | |
public static <T extends CompletableFuture<?>> Collector<T, ?, CompletableFuture<Void>> allComplete(){ | |
return Collectors.collectingAndThen(Collectors.toList(), CompletableFutureCollector::allOf); | |
} | |
private static <X, T extends CompletableFuture<X>> Function<List<T>, CompletableFuture<List<X>>> joinResult() { | |
return ls-> allOf(ls) | |
.thenApply(v -> ls | |
.stream() | |
.map(CompletableFuture::join) | |
.collect(Collectors.toList())); | |
} | |
private static <T extends CompletableFuture<?>> CompletableFuture<Void> allOf(List<T> ls) { | |
return CompletableFuture.allOf(ls.toArray(new CompletableFuture[ls.size()])); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment