In Java 8, the Function
interface is a part of the java.util.function
package and is used to represent a function that accepts one argument and produces a result. It is a functional interface, meaning it has a single abstract method that can be implemented using a lambda expression or method reference.
Functional Interface Definition
The Function
interface is defined as follows:
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
// Other default and static methods can be included
}
Here, T
is the type of the input to the function, and R
is the type of the result of the function.
Key Methods
-
apply(T t): This is the abstract method that applies the function to the given argument and returns the result.
-
andThen(Function<? super R, ? extends V> after): This default method returns a composed function that first applies this function to its input, and then applies the
after
function to the result. -
compose(Function<? super V, ? extends T> before): This default method returns a composed function that first applies the
before
function to its input, and then applies this function to the result.
Example Usage
Here's a simple example of how to use the Function
interface in Java 8:
import java.util.function.Function;
public class FunctionExample {
public static void main(String[] args) {
// Creating a Function that converts a String to its length
Function<String, Integer> stringLength = str -> str.length();
// Applying the Function
Integer length = stringLength.apply("Hello, Java 8!");
System.out.println("Length of the string: " + length);
// Creating another Function that squares a number
Function<Integer, Integer> square = num -> num * num;
// Composing functions: first get the length, then square it
Function<String, Integer> lengthSquared = stringLength.andThen(square);
Integer squaredLength = lengthSquared.apply("Hello, Java 8!");
System.out.println("Squared length of the string: " + squaredLength);
}
}
Explanation
-
Function<String, Integer> stringLength: This function takes a
String
as input and returns its length as anInteger
. -
apply method: The
apply
method is used to execute the function with the given input. -
Function<Integer, Integer> square: This function takes an
Integer
as input and returns its square. -
andThen method: The
andThen
method is used to compose two functions. In this example, it first applies thestringLength
function and then applies thesquare
function to the result.
Practical Use Cases
- Data transformation: Functions can be used to transform data from one form to another, such as converting objects to their string representations or parsing strings to create objects.
- Stream API: The
Function
interface is widely used in the Java 8 Stream API for operations likemap
andflatMap
.
By leveraging the Function
interface and its associated methods, you can create more readable and maintainable code that follows the functional programming paradigm introduced in Java 8.