我有想要重构为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()));
答案 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
的命令式方法真的很慢吗?