Here you can find the source of sequence(List
public static <T> CompletableFuture<List<T>> sequence(List<CompletableFuture<T>> futures)
//package com.java2s; /*/*from w w w . j a va 2 s . c o m*/ * Copyright (c) 2016 Kevin Herron * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v1.0 which accompany this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.html. */ import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; public class Main { public static <T> CompletableFuture<List<T>> sequence(List<CompletableFuture<T>> futures) { if (futures.isEmpty()) { return CompletableFuture.completedFuture(Collections.emptyList()); } CompletableFuture[] fa = futures.toArray(new CompletableFuture[futures.size()]); return CompletableFuture.allOf(fa).thenApply(v -> { List<T> results = new ArrayList<>(futures.size()); for (CompletableFuture<T> cf : futures) { results.add(cf.join()); } return results; }); } public static <T> CompletableFuture<List<T>> sequence(CompletableFuture<T>[] futures) { if (futures.length == 0) { return CompletableFuture.completedFuture(Collections.emptyList()); } return CompletableFuture.allOf(futures).thenApply(v -> { List<T> results = new ArrayList<>(futures.length); for (CompletableFuture<T> cf : futures) { results.add(cf.join()); } return results; }); } }