Java CompletableFuture thenApply()

By Arvind Rai, May 21, 2019
Java CompletableFuture inherits CompletionStage and Future interfaces. CompletableFuture.thenApply is inherited from CompletionStage. The thenApply returns a new CompletionStage that, when this stage completes normally, is executed with this stage's result as the argument to the supplied function.
Find the method declaration of thenApply from Java doc.
<U> CompletionStage<U> thenApply(Function<? super T,? extends U> fn) 
The type parameter U is the function's return type.
The fn parameter is the function to use to compute the value of the returned CompletionStage.
The thenApply method returns a CompletionStage.

thenApply() can be used to perform some extra task on the result of another task. Now find the examples.
Example-1: We create a CompletionStage to perform some task and then on the result of this stage we apply a function to perform other task using thenApply. Find the example.
ThenApplyDemo1.java
package com.concretepage;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class ThenApplyDemo1 {
  public static void main(String[] args) throws InterruptedException, ExecutionException {
	
	CompletableFuture<String> cfuture = 
		CompletableFuture.supplyAsync(() -> "Krishna").thenApply(data -> "Shri "+ data); 
	
	String msg = cfuture.get();
	System.out.println(msg);
  }
} 
Output
Shri Krishna 

Example-2:
ThenApplyDemo2.java
package com.concretepage;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class ThenApplyDemo2 {
  public static void main(String[] args) throws InterruptedException, ExecutionException {
	
	CompletableFuture<String> cfuture = 
		CompletableFuture.supplyAsync(() -> computeArea(20, 30)).thenApply(data -> prettyPrint(data)); 
	
	String msg = cfuture.get();
	System.out.println(msg);
  }
  private static int computeArea(int a, int b) {
	return a * b;
  }
  private static String prettyPrint(int area) {
	return "Area: "+ area;
  }  
} 
Output
Area: 600 

Example-3:
ThenApplyDemo3.java
package com.concretepage;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class ThenApplyDemo3 {
  public static void main(String[] args) throws InterruptedException {
	List<Integer> list = Arrays.asList(10, 20, 30, 40);
	list.stream().map(num -> CompletableFuture.supplyAsync(() -> num * num))
		.map(cfuture -> cfuture.thenApply(res -> "Square: " + res)).map(t -> t.join())
		.forEach(s -> System.out.println(s));
  }
} 
Output
Square: 100
Square: 400
Square: 900
Square: 1600 

References

Java Doc: Class CompletableFuture
Java CompletableFuture supplyAsync()
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us