Java8中的CompletableFuture

时间:2018-11-30 13:13:07

标签: java java-8 java-stream completable-future

我有想要重构为Java 8的这段代码

List<String> menus = new ArrayList<String>();           
for (Menu menu : resto1.getMenu()) {            
    MainIngredient mainIngredient = MainIngredient.getMainIngredient(menu.getName());           
    if (mainIngredient.getIngredient().indexOf("Vegan")!=-1) {
        menus.add(menu.getName());
    }                   
}

重构此简单循环后,似乎有太多代码……我正确使用了CompletableFutures吗?

ExecutorService executorService = Executors.newCachedThreadPool();
List<CompletableFuture<MainIngredient>> priceFutureList = resto1.getMenu().stream()
    .map(menu -> CompletableFuture.supplyAsync(
        () -> MainIngredient.getMainIngredient(menu.getName()), executorService))
    .collect(Collectors.toList());        

CompletableFuture<Void> allFuturesDone = CompletableFuture.allOf(
    priceFutureList.toArray(new CompletableFuture[priceFutureList.size()]));

CompletableFuture<List<MainIngredient>> priceListFuture =        
    allFuturesDone.thenApply(v -> priceFutureList.stream()
        .map(CompletableFuture::join)
        .collect(toList()));

1 个答案:

答案 0 :(得分:8)

为什么不只是?

List<String> menus = resto1.getMenu()
                           .stream()
                           .map(m -> MainIngredient.getMainIngredient(m.getName()))
                           .filter(m -> m.getIngredient().indexOf("Vegan")!=-1)
                           .collect(toCollection(ArrayList::new));

您必须使用CompletableFuture的命令式方法真的很慢吗?