Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2016 BestSolution.at and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Tom Schindl <tom.schindl@bestsolution.at> - initial API and implementation
 *******************************************************************************/

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
    /**
     * Collect the return values of all the futures provided
     *
     * @param futures
     *            the futures the result is collected from
     * @return a future with the collected results
     */
    @SafeVarargs
    public static <T> CompletableFuture<List<T>> collect(CompletableFuture<T>... futures) {
        return CompletableFuture.allOf(futures)
                .thenApply(v -> Stream.of(futures).map(f -> f.join()).collect(Collectors.toList()));
    }

    /**
     * Collect the return value of all the futures and apply the transformation
     * method on it
     *
     * @param transformer
     *            the transformation to apply
     * @param futures
     *            the future
     * @return a future with the collected results
     */
    @SafeVarargs
    public static <T, O> CompletableFuture<List<T>> collect(Function<O, T> transformer,
            CompletableFuture<O>... futures) {
        return CompletableFuture.allOf(futures).thenApply(
                v -> Stream.of(futures).map(f -> f.join()).map(transformer::apply).collect(Collectors.toList()));
    }
}