Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Function.andThen — run this function first, then the next

`Function.andThen` returns a composed function that runs the receiver first and passes its result to the `after` function.

Version: Java SE 21

Syntax

default <V> Function<T, V> andThen(Function<? super R, ? extends V> after)

Function.andThen is a default method of java.util.function.Function<T, R>. Calling f.andThen(g) returns a composed function without running f or g. Calling apply(x) on that function evaluates g.apply(f.apply(x)): f (this) runs first, then g (after).

The input type T stays the same. The after function must be able to accept the R result: its input type can be R or a supertype of R (? super R). It can return V or a subtype of V (? extends V). The composed function has type Function<T, V>.

With f.compose(g), the order is reversed: g runs first, then f. When the types fit, f.andThen(g) and g.compose(f) perform the same steps in the same order.

If after is null, andThen throws NullPointerException when you create the composition. If the first stage throws during apply, the second stage does not run. An exception from either stage propagates to the caller of the composed function. A null result from the first stage does not stop evaluation: it is passed to the second function.

Examples

import java.util.function.Function;

public class AndThenDemo {
    public static void main(String[] args) {
        Function<String, String> strip = String::strip;
        Function<String, Integer> length = String::length;

        Function<String, Integer> strippedLength = strip.andThen(length);
        System.out.println(strippedLength.apply(" Java "));
    }
}

Result

4

`strip` removes the spaces at both ends of `" Java "`, then `length` measures the resulting `"Java"`. The expected output is `4`, not `6`.

Related lessons

  • Java · Lesson 48 · Intermediate · Version: 2

Sources