thenApplyおよびのthenComposeメソッドですCompletableFuture。でCompleteableFuture結果に何かをするつもりの場合に使用しますFunction。
thenApplyそして、thenComposeの両方が返されCompletableFuture、自分の結果として。複数thenApplyまたはthenCompose一緒にチェーンできます。Function各呼び出しにa を指定します。その結果は次への入力になりFunctionます。
Functionあなたは時々供給は同期何かをする必要があります。の戻り型はFunction非Future型でなければなりません。この場合、を使用する必要がありますthenApply。
CompletableFuture.completedFuture(1)
.thenApply((x)->x+1) // adding one to the result synchronously, returns int
.thenApply((y)->System.println(y)); // value of y is 1 + 1 = 2
場合によっては、これで非同期処理を実行することもできますFunction。その場合はを使用する必要がありますthenCompose。の戻り値の型はであるFunction必要がありCompletionStageます。Functionチェーンの次は、その結果をCompletionStage入力として取得し、をアンラップしCompletionStageます。
// addOneAsync may be implemented by using another thread, or calling a remote method
abstract CompletableFuture<Integer> addOneAsync(int input);
CompletableFuture.completedFuture(1)
.thenCompose((x)->addOneAsync(x)) // doing something asynchronous, returns CompletableFuture<Integer>
.thenApply((y)->System.println(y)); // y is an Integer, the result of CompletableFuture<Integer> above
これはJavascriptのアイデアに似ていPromiseます。Promise.thenは、値または値のいずれかを返す関数を受け入れることができPromiseます。Javaでこれら2つのメソッドの名前が異なる理由は、一般的な消去によるものです。です。Function<? super T,? extends U> fnとFunction<? super T,? extends CompletionStage<U>> fn同じランタイムタイプと見なされFunctionます- 。したがってthenApply、thenCompose明確に名前を付ける必要があります。そうしないと、Javaコンパイラが同一のメソッドシグネチャについて文句を言うでしょう。最終結果ビーイングは、JavascriptののはPromise.then二つの部分に実装されて- thenApplyとthenCompose- Javaで。
あなたは読むことができます 関連する機能についても混乱している場合は、他の回答thenApplyAsync。
mapとflatMapではStream?thenApplyであるmapとthenComposeあるflatMapのCompletableFuture。thenComposeを避けるために使用しCompletableFuture<CompletableFuture<..>>ます。