gpt4 book ai didi

java - 在 Java8 循环中转换旧循环

转载 作者:行者123 更新时间:2023-11-30 06:42:21 25 4
gpt4 key购买 nike

我是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());

关于java - 在 Java8 循环中转换旧循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53556769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com