The Java Function
interface of the java.util.function
package is a functional interface that is often used as an assignment target for lambda expressions. The apply(T t)
method is the class’s only abstract method, leaving it as the only one without a default implementation. Here is an overview of the various methods in the Function interface:
applyt(T t)
is the interface’s single abstract method which takes an object and returns an object.compose(Function<? super V,? extends T> before)
returns another Function object. First thebefore
Function is applied to input, then the calling Function is applied to the result.andThen(Function<? super R,? extends V> after)
returns another Function object. First the calling function is applied to the input, then theafter
function is applied to the result.identity()
returns a function that simply returns the its input argument
For more information on functional interfaces in Java click here: What is a Java Functional Interface?.
For more information on lambdas in Java click here: What are Lambdas in Java?
Function Interface Source Code
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
default Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
default Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
static Function<T, T> identity() {
return t -> t;
}
}
Function Interface Example
Below is an example of creating the FunctionExample
class by implementing Function
. This apply(T t)
method takes a string and returns an Integer.
public class FunctionExample implements Function<String, Integer> {
public Integer apply(String s) {
return Integer.parseInt(s);
}
}
Creating a Function Instance with Lambda Expression
Below is an example of using a lambda expression to create an instance of Function
. This apply(T t)
method takes a string and returns an Integer.
Function<String, Integer> function = t -> Integer.parseInt(t);