What Is a Function Interface In Java?
This lesson talks about the third functional interface, which is the Function.
Table of Contents
What is a Function interface?
The function interface is a function that maps a value to a different value. Accepts one argument and produces a result.
The Function
interface is a functional interface defined in the java.util.function
package. It represents a function that accepts an input of one type and produces a result of another type.
The Function
interface is widely used in functional programming scenarios where you need to transform or convert data from one form to another.
The Function
interface declares a single abstract method called apply()
, which takes an argument of the input type and returns a value of the result type. Here's the method signature of the apply()
method:
Syntax
R apply(T t);
The type parameters T
and R
represent the input type and result type, respectively. They can be any valid Java type, including primitive types and objects.
To use the Function
interface, you can create an instance of it using a lambda expression or method reference that implements the apply()
method. Here's an example that demonstrates how to use a Function
to convert a string to its length:
import java.util.function.Function;
public class FunctionExample {
public static void main(String[] args) {
Function<String, Integer> stringLengthFunction = str -> str.length();
// Calling the apply() method to get the length of a string
int length = stringLengthFunction.apply("Hello, World!");
System.out.println("Length: " + length); // Length: 13
}
}
In the example, we create a Function<String, Integer>
using a lambda expression that takes a string as input and returns its length using the length()
method of the String
class. Then, we call the apply()
method on the Function
instance to obtain the length of a given string.
The Function
interface is commonly used in functional programming and enables a wide range of transformations and mappings on data. It can be used to transform one type to another, apply calculations or algorithms, or perform any custom processing that involves input and output data.
Note that the Function
interface is part of the Java 8 functional interfaces introduced to support lambda expressions and functional programming constructs. It is often used in combination with other functional interfaces like Consumer
, Supplier
, and Predicate
to compose complex functional pipelines and perform data manipulation in a concise and expressive manner.
👨🏻💻 Gopi Gorantala Newsletter
Join the newsletter to receive the latest updates in your inbox.