Last active
May 22, 2021 20:52
-
-
Save jklingsporn/f82b5248f33e0f23a15e33af1429dce3 to your computer and use it in GitHub Desktop.
Converts a Stream<CompletableFuture<X>> to a CompletableFuture<List<X>>
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.ArrayList; | |
import java.util.Collections; | |
import java.util.List; | |
import java.util.Set; | |
import java.util.concurrent.CompletableFuture; | |
import java.util.function.BiConsumer; | |
import java.util.function.BinaryOperator; | |
import java.util.function.Function; | |
import java.util.function.Supplier; | |
import java.util.stream.Collector; | |
import java.util.stream.Collectors; | |
public class CompletableFutureCollector<X, T extends CompletableFuture<X>> implements Collector<T, List<T>, CompletableFuture<List<X>>> { | |
private CompletableFutureCollector(){ | |
} | |
public static <X, T extends CompletableFuture<X>> Collector<T, List<T>, CompletableFuture<List<X>>> allOf(){ | |
return new CompletableFutureCollector<>(); | |
} | |
@Override | |
public Supplier<List<T>> supplier() { | |
return ArrayList::new; | |
} | |
@Override | |
public BiConsumer<List<T>, T> accumulator() { | |
return List::add; | |
} | |
@Override | |
public BinaryOperator<List<T>> combiner() { | |
return (left, right) -> { left.addAll(right); return left; }; | |
} | |
@Override | |
public Function<List<T>, CompletableFuture<List<X>>> finisher() { | |
return ls->CompletableFuture.allOf(ls.toArray(new CompletableFuture[ls.size()])) | |
.thenApply(v -> ls | |
.stream() | |
.map(CompletableFuture::join) | |
.collect(Collectors.toList())); | |
} | |
@Override | |
public Set<Characteristics> characteristics() { | |
return Collections.emptySet(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks!