Completable Future

In Java CompletableFutures, the methods apply(), accept(), and run() are used to handle the results of a computation or task when it completes. Here's the difference between these methods:

  1. apply(): This method is used when you want to apply a function to the result of a computation and return a new CompletableFuture with the transformed result. It takes a Function as a parameter that specifies how to transform the result. The apply() method returns a CompletableFuture that will eventually hold the transformed result.

Example usage:

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5);
CompletableFuture<String> transformedFuture = future.thenApply(result -> result * 2)
                                                  .thenApply(result -> "Transformed: " + result);
  1. accept(): This method is used when you want to perform an action with the result of a computation, but you don't need to return anything. It takes a Consumer as a parameter that specifies the action to be performed on the result. The accept() method returns a CompletableFuture that completes when the action is done.

Example usage:

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5);
CompletableFuture<Void> actionFuture = future.thenAccept(result -> System.out.println("Result: " + result));
  1. run(): This method is used when you want to perform an action after the completion of a computation, without using the result of the computation. It takes a Runnable as a parameter that specifies the action to be performed. The run() method returns a CompletableFuture that completes when the action is done.

Example usage:

CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> 5)
                                                 .thenRun(() -> System.out.println("Computation completed"));

In summary, apply() is used when you want to transform the result and return a new CompletableFuture, accept() is used when you want to perform an action with the result, and run() is used when you want to perform an action without using the result.

Last updated