【Java 8 新特性】Java CompletableFuture thenApply()

Java CompletableFuture继承了CompletionStageFuture接口。

CompletableFuture.thenApply继承自CompletionStage

thenApply返回一个新的CompletionStage,当该阶段正常完成时,将使用该阶段的结果作为所提供函数的参数来执行该过程。

Java文档中找到thenApply的方法声明。

<U> CompletionStage<U> thenApply(Function<? super T,? extends U> fn) 

类型参数U是函数的返回类型。

fn参数是用于计算返回的CompletionStage的值的函数。

thenApply方法返回CompletionStage

thenApply()可用于对另一个任务的结果执行一些额外的任务。

示例1: 我们创建一个CompletionStage来执行某些任务,然后在此阶段的结果上,我们使用thenApply应用函数来执行其他任务。

ThenApplyDemo1.java

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);
  }
} 

输出

Shri Krishna 

示例2:

ThenApplyDemo2.java

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;
  }  
} 

输出

Area: 600 

示例3:

ThenApplyDemo3.java

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));
  }
} 

输出

Square: 100
Square: 400
Square: 900
Square: 1600 

参考文献

【1】Java Doc: Class CompletableFuture
【2】Java CompletableFuture supplyAsync()
【3】Java CompletableFuture thenApply()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猫巳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值