我是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>>
答案 0 :(得分:4)
在第一个解决方案中,您缺少collect(toList())
:
List<CompletableFuture<MainIngredient>> priceFutureList = resto1.getMenu().stream()
.map(menu -> CompletableFuture.supplyAsync(() -> MainIngredient.getMainIngredient(menu.getName()), executorService))
.collect(Collectors.toList());