Function
A function that takes a value of type `T` and returns a value of type `R`.
Available since: Java 8
Syntax
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}Examples
Calling and composing:
void main() {
Function<String, Integer> length = String::length;
Function<Integer, Integer> doubled = n -> n * 2;
IO.println(length.apply("hello"));
IO.println(length.andThen(doubled).apply("hello"));
}Output:
5
10Notes
andThen(g) runs this function first and then g; compose(g) runs them the other way round. Function.identity() returns its argument unchanged. For primitives there are specialized versions without boxing: IntFunction, ToIntFunction, IntUnaryOperator.
See also
- BiFunction — A function of two arguments.
- UnaryOperator — A function whose argument and result have the same type.
- Stream.map() — Transforms every element of a stream.
- -> (lambda) — A lambda expression — a short function that can be passed around as a value.
Related recipes
In the tutorial
- Functional interfaces — Functional interfaces in Java: the @FunctionalInterface annotation, the standard Function, Predicate, Consumer, Supplier and combining them.