上一篇文章,讲述了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
<