What is the Java Function Interface?

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 the before 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 the after 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

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.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">