首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CompletableFuture in Java8

CompletableFuture in Java8
EN

Stack Overflow用户
提问于 2018-11-30 13:13:07
回答 1查看 238关注 0票数 8

我有一段代码想要重构成Java 8

代码语言:javascript
复制
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吗?

代码语言:javascript
复制
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()));
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-30 13:17:34

为什么不只是?

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

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

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53558282

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档