Created
December 17, 2019 16:47
-
-
Save leandrob13/565baaddd943852e6dcedf2fb76739ab to your computer and use it in GitHub Desktop.
Example of sequence and traverse for java's CompletableFuture.
This file contains hidden or 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.List; | |
import java.util.concurrent.CompletableFuture; | |
import java.util.function.Function; | |
public class FutureOps { | |
public static <T> CompletableFuture<List<T>> sequence(List<CompletableFuture<T>> ls) { | |
return ls.stream() | |
.reduce( | |
CompletableFuture.completedFuture(new ArrayList<T>(ls.size())), | |
(fs, fa) -> fs.thenCombine(fa, (s, a) -> {s.add(a); return s;}), | |
(fa, fb) -> fa.thenCombine(fb, (a, b) -> {a.addAll(b); return a;}) | |
).thenApply(List::copyOf); | |
} | |
public static <T, V> CompletableFuture<List<V>> traverse(List<T> ls, Function<T, CompletableFuture<V>> fn) { | |
return ls.stream() | |
.reduce( | |
CompletableFuture.completedFuture(new ArrayList<V>(ls.size())), | |
(fs, a) -> fs.thenCombine(fn.apply(a), (s, f) -> {s.add(f); return s;}), | |
(fa, fb) -> fa.thenCombine(fb, (a, b) -> {a.addAll(b); return a;}) | |
).thenApply(List::copyOf); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, very helpful :)