CKTIS / Java
Functions and functional interfaces in Java
Functions and functional interfaces in Java: Java represents behavior with methods and with lambdas or method references targeted to a functional interface having one abstract method.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
functionsJava represents behavior with methods and with lambdas or method references targeted to a functional interface having one abstract method.
Choose Predicate, Function, Consumer, Supplier, and primitive specializations, and compose small functions with compose or andThen. A variable-arity parameter T... must be last, is treated as T[], and accepts zero or many arguments.
A lambda captures only final or effectively final local variables; a captured mutable object still needs synchronization under concurrency.
Lambda object identity is unspecified, this refers to the enclosing object, a checked exception must fit the interface signature, and passing null to varargs may mean a null array reference.
andThen produces 11, while the int... method proves that zero- and three-argument calls return 0 and 6.
Examples
import java.util.Arrays;
import java.util.function.IntUnaryOperator;
public class Main {
static int sum(int... values) {
return Arrays.stream(values).sum();
}
public static void main(String[] args) {
int base = 3;
IntUnaryOperator twice = x -> x * 2;
IntUnaryOperator plusBase = x -> x + base;
System.out.println(twice.andThen(plusBase).applyAsInt(4));
System.out.println(sum());
System.out.println(sum(1, 2, 3));
}
}
Result
11 0 6
andThen produces 11, while the int... method proves that zero- and three-argument calls return 0 and 6.