java 异步 map_Java8新的异步编程方式 CompletableFuture(二)

本文深入探讨了Java8的CompletableFuture,特别是其转换特性,包括map和flatMap方法,以及如何组合多个CompletableFuture。示例代码详细解释了如何使用这些方法进行数据转换和组合操作。
摘要由CSDN通过智能技术生成

上一篇文章,讲述了Future模式的机制、缺点,CompletableFuture产生的由来、静态工厂方法、complete()方法等等。

本文将继续整理CompletableFuture的特性。

3.3 转换

我们可以通过CompletableFuture来异步获取一组数据,并对数据进行一些转换,类似RxJava、Scala的map、flatMap操作。

3.3.1 map

方法名

描述

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

接受一个Function super T,? extends U>参数用来转换CompletableFuture

thenApplyAsync(Function super T,? extends U> fn)

接受一个Function super T,? extends U>参数用来转换CompletableFuture,使用ForkJoinPool

thenApplyAsync(Function super T,? extends U> fn, Executor executor)

接受一个Function super T,? extends U>参数用来转换CompletableFuture,使用指定的线程池

thenApply的功能相当于将CompletableFuture转换成CompletableFuture

CompletableFuture future = CompletableFuture.supplyAsync(() -> "Hello");

future = future.thenApply(new Function() {

@Override

public String apply(String s) {

return s + " World";

}

}).thenApply(new Function() {

@Override

public String apply(String s) {

return s.toUpperCase();

}

});

try {

System.out.println(future.get());

} catch (InterruptedException e) {

e.printStackTrace();

} catch (ExecutionException e) {

e.printStackTrace();

}

再用lambda表达式简化一下

CompletableFuture future = CompletableFuture.supplyAsync(() -> "Hello")

.thenApply(s -> s + " World").thenApply(String::toUpperCase);

try {

System.out.println(future.get());

} catch (InterruptedException e) {

e.printStackTrace();

} catch (ExecutionException e) {

e.printStackTrace();

}

执行结果:

HELLO WORLD

下面的例子,展示了数据流的类型经历了如下的转换:String -> Integer -> Double。

CompletableFuture future = CompletableFuture.supplyAsync(() -> "10")

.thenApply(Integer::parseInt)

.thenApply(i->i*10.0);

try {

System.out.println(future.get());

} catch (InterruptedException e) {

e.printStackTrace();

} catch (ExecutionException e) {

e.printStackTrace();

}

执行结果:

100.0

<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值