All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.pivovarit.collectors.FutureCollectors Maven / Gradle / Ivy

The newest version!
package com.pivovarit.collectors;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * @author Grzegorz Piwowarek
 */
final class FutureCollectors {
    static  Collector, ?, CompletableFuture> toFuture(Collector collector) {
        return Collectors.collectingAndThen(toList(), list -> {
            var future = CompletableFuture.allOf(list.toArray(CompletableFuture[]::new))
              .thenApply(__ -> list.stream()
                .map(CompletableFuture::join)
                .collect(collector));

            for (var f : list) {
                f.whenComplete((__, throwable) -> {
                    if (throwable != null) {
                        future.completeExceptionally(throwable);
                    }
                });
            }

            return future;
        });
    }

    static  Collector, ?, CompletableFuture>> toFuture() {
        return toFuture(toList());
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy