Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CompletableFuture in Java8

I have this piece of code that I wanted to refactor to 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());
    }                   
}

After refactoring this simple loop it seems like too much code... am I using CompletableFutures correctly?

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()));
like image 393
carles xuriguera Avatar asked Nov 30 '18 13:11

carles xuriguera


Video Answer


1 Answers

Why not just?

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

is your imperative approach really slow that you have to use CompletableFuture?

like image 108
Ousmane D. Avatar answered Oct 29 '22 18:10

Ousmane D.