将旧循环转换为 Java8 循环

Converting a old loop in a Java8 loop

我是新手Java8,我有这段代码

for (Menu menu : resto1.getMenu()) {
    MainIngredient mainIngredient = MainIngredient.getMainIngredient(menu.getName());
}

我想重构以使其更快,并且我想将其转换为

List<CompletableFuture<MainIngredient>>

我试过了

List<CompletableFuture<MainIngredient>> priceFutureList = resto1.getMenu().stream()
            map(menu -> CompletableFuture.supplyAsync(() -> MainIngredient.getMainIngredient(menu.getName()), executorService));

但是我得到了这个错误:

 Type mismatch: cannot convert from Stream<Menu> to 
     List<CompletableFuture<MainIngredient>>

然后我也试了这个

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

但我得到的是 CompletableFuture<List<MainIngredient>> 而不是 List<CompletableFuture<MainIngredient>>

在您的第一个解决方案中,您缺少 collect(toList()):

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