CKTIS / Java
Function.apply — call a function
`apply` takes one argument and returns the function's result. Use it to call a single function or run a previously composed chain of functions.
Version: Java SE 21
Syntax
R apply(T t)
R result = function.apply(argument); // function: Function<T, R>In Java SE 21, java.util.function.Function<T, R> is a functional interface with the abstract method R apply(T t). In function.apply(argument), the argument must be compatible with T, and the result has type R. A lambda expression or method reference can supply the implementation.
The instance method apply has no zero-argument overload. If function has type Function<T, R>, function.apply() does not compile.
f.andThen(g) builds a composed function that runs f first and then g. f.compose(g) reverses the order: g first, then f. The first stage's result must be compatible with the second stage's input type. Building the chain does not run its stages; calling apply with an argument on the composed function does. If either stage throws an exception, it propagates to the caller.
Examples
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
Function<String, Integer> length = String::length;
Function<Integer, String> label = n -> "Length: " + n;
Function<String, String> pipeline = length.andThen(label);
System.out.println(length.apply("Java"));
System.out.println(pipeline.apply("Java"));
}
}Result
4 Length: 4
`length.apply("Java")` returns `4`. `pipeline.apply("Java")` passes that `4` to `label` and returns the text `Length: 4`.
Related lessons
- Java · Lesson 62 · Basic · Version: 2
- Java · Lesson 48 · Intermediate · Version: 2