Function and BiFunction
Transform values functionally.
What Function Represents
Function<T, R> is the core transformation interface in java.util.function. It takes one argument of type T and returns a result of type R.
- Its single abstract method is
R apply(T t). - It models a pure mapping from input to output.
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
Function<String, Integer> length = s -> s.length();
System.out.println(length.apply("hello"));
}
}Calling apply
You invoke a Function by calling apply. The lambda body is the transformation logic.
- Input and output types can differ.
- A method reference like
String::toUpperCasecan replace a lambda.
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
Function<String, String> upper = String::toUpperCase;
System.out.println(upper.apply("java"));
}
}All lessons in this course
- Function and BiFunction
- Supplier and Consumer
- Predicate and Composition
- Custom Functional Interfaces