MST

星途 面试题库

面试题:Java中CompletableFuture的thenApply如何实现基本数据转换

假设有一个CompletableFuture<Integer>,值为5,现在要通过thenApply方法将其转换为String类型,值为其平方的字符串形式(如"25"),请写出实现代码。并说明thenApply方法的参数类型和返回值类型。
21.0万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> 5)
  .thenApply(i -> String.valueOf(i * i));
  • thenApply方法的参数类型:Function<? super T,? extends U>,这里TIntegerFunction接收一个Integer类型参数并返回一个U类型(这里UString)。
  • thenApply方法的返回值类型:CompletableFuture<U>,这里UString,即返回一个CompletableFuture<String>