CKTIS / Java
Function — transforming values and composing functions
Function<T, R> describes an operation that accepts one argument and returns a result. Learn apply, the execution order of andThen and compose, and the identity function.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
Function<T, R> f = value -> expression;
R apply(T t)
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after)
default <V> Function<V, R> compose(Function<? super V, ? extends T> before)
static <T> Function<T, T> identity()java.util.function.Function<T, R> is a functional interface: it accepts an argument of type T and returns a result of type R. Implement it with a lambda or method reference. Function.apply (f.apply(value)) executes the operation.
Function.andThen creates a composition: f.andThen(g).apply(x) computes g.apply(f.apply(x)). Function.compose reverses the order: f.compose(g).apply(x) computes f.apply(g.apply(x)). Connected stages must have compatible types; composition itself does not execute the operations on an argument.
The static method Function.identity() returns a function that returns its argument unchanged, not a copy.
Passing null as the function to andThen or compose causes NullPointerException. Exceptions during stage execution propagate to the caller. This does not imply a general ban on null arguments to apply: their handling depends on the implementation.
Examples
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
Function<Integer, Integer> increment = x -> x + 1;
Function<Integer, Integer> doubleValue = x -> x * 2;
Function<Integer, Integer> unchanged = Function.identity();
System.out.println(increment.apply(3));
System.out.println(increment.andThen(doubleValue).apply(3));
System.out.println(increment.compose(doubleValue).apply(3));
System.out.println(unchanged.apply(3));
}
}Result
4 8 7 3
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.