CompletionStage: Why is allOf or anyOf defined in CompletableFuture [closed]

孤街浪徒 提交于 2019-12-05 18:11:55

If all you want, is a method providing the same anyOf and allOf functionality for objects of the type CompletionStage, you can simply resort to toCompletableFuture:

public static CompletionStage<Object> anyOf(CompletionStage<?>... css) {
    return CompletableFuture.anyOf(Arrays.stream(css)
        .map(CompletionStage::toCompletableFuture).toArray(CompletableFuture[]::new));
}
public static CompletionStage<Void> allOf(CompletionStage<?>... css) {
    return CompletableFuture.allOf(Arrays.stream(css)
        .map(CompletionStage::toCompletableFuture).toArray(CompletableFuture[]::new));
}

Here is what I've come up with

/**
 * A class with several helper methods for working with {@link CompletionStage}
 */
public class CompletionStages {


    public static CompletionStage<Object> anyOf(CompletionStage... completionStages) {
        if (completionStages == null) {
            throw new IllegalArgumentException("You must pass a non-null argument for completionStages");
        }
        if (completionStages.length == 0) {
            throw new IllegalArgumentException("You must pass a non-empty argument for completionStages");
        }

        CompletableFuture result = new CompletableFuture();
        for(CompletionStage completionStage : completionStages) {
            completionStage.thenAccept( r -> result.complete(r));
        }
        return result;
    }


    public static CompletionStage<Void> allOf(CompletionStage... completionStages) {
        if (completionStages == null) {
            throw new IllegalArgumentException("You must pass a non-null argument for completionStages");
        }
        if (completionStages.length == 0) {
            throw new IllegalArgumentException("You must pass a non-empty argument for completionStages");
        }

        CompletionStage result = CompletableFuture.completedFuture(null);
        for(int i = 0; i < completionStages.length; i++) {
            CompletionStage curr = completionStages[i];
            result = result.thenAcceptBoth(curr, (o, o2) -> {});
        }
        return result;
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!