79424628

Date: 2025-02-09 08:58:26
Score: 1
Natty:
Report link

I am late to the party but here are my 2 cents

I am writing here about these three methods—thenApply(), thenCompose(), and thenCombine().. They might seem similar initially, but they serve distinct purposes.

1. thenApply()

Example:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hi Buddy")
    .thenApply(result -> result + " .How are you?");

future.thenAccept(System.out::println); 

2. thenCompose()

Example:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "hi")
    .thenCompose(result -> CompletableFuture.supplyAsync(() -> result + " .. hows life???"));

future.thenAccept(System.out::println);

Here, thenCompose() chains two asynchronous tasks. The second CompletableFuture depends on the result of the first.

Why flatten? Without thenCompose(), you'd end up with CompletableFuture<CompletableFuture<String>>, which isn't useful.


3. thenCombine()

Example:

CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 1);
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 2);

CompletableFuture<Integer> combinedFuture = future1.thenCombine(future2, (result1, result2) -> result1 + result2);

combinedFuture.thenAccept(System.out::println); // prints 3

Here, thenCombine() takes the results of two independent tasks (future1 and future2) and combines them into a single result (3).


Summary: When to Use What

Reasons:
  • Blacklisted phrase (1): ???
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (1):
Posted by: Amit