多个泛型CompletableFuture获取结果

获取feed列表通常里边需要依据Id查询用户信息

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicLong;

public class BatchCompletableFutureTest {

    private static AtomicLong  sample= new AtomicLong(0);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println(batchGetFutute().get());
    }

    private static CompletableFuture<Map<String,String>>  batchGetFutute(){
        Map<String,CompletableFuture<Map<String,String>>> batchFutureMap = new HashMap<>();
        for (int i=1; i<=10;i++){
            CompletableFuture<Map<String,String>> mapFuture = getMapFuture();
            batchFutureMap.put(String.valueOf(i),mapFuture);
        }

        CompletableFuture<Map<String,String>>[] batchFutureMapArray =  new CompletableFuture[batchFutureMap.size()];
        batchFutureMap.values().toArray(batchFutureMapArray);
        
        return CompletableFuture.allOf(batchFutureMapArray).thenApply(x ->{
            Map<String,String> ret = new HashMap<>();
            for (int i=0; i<batchFutureMapArray.length;i++){
                ret.putAll(batchFutureMapArray[i].join());
            }
            return ret;
        });
    }

    private static CompletableFuture<Map<String,String>> getMapFuture(){
        return CompletableFuture.supplyAsync(() ->{
            Map<String,String> ret = new HashMap<>();
            ret.put("k_"+String.valueOf(sample.getAndIncrement()),String.valueOf(System.currentTimeMillis()));
            return ret;
        });
    }
}

结果

{k_5=1590482981704, k_4=1590482981659, k_7=1590482981668, k_6=1590482981668, k_9=1590482981668, k_8=1590482981668, k_1=1590482981658, k_0=1590482981658, k_3=1590482981658, k_2=1590482981658}

 

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页