Java Functional Interface¶
A Java Functional Interface is an interface that serves as the foundation for Lambda expressions and method references in Java, effectively allowing behavior to be passed as a method argument.^[600-developer__java__java8__java8-lambda.md]
In Java development, this concept is often compared to JavaScript's callback function mechanism.^[600-developer__java__java8__java8-lambda.md] While JavaScript passes functions directly as callbacks, Java achieves this "callback" style behavior by passing functional interfaces or Lambda expressions.^[600-developer__java__java8__java8-lambda.md]
Core Concept¶
The primary utility of functional interfaces is to abstract actions or methods, allowing them to be passed into other methods just like data variables.^[600-developer__java__java8__java8-lambda.md] This enables a pattern where the specific implementation of an action is defined by the caller at runtime, facilitating dynamic behavior execution within a method.
Common Built-in Functional Interfaces¶
Java provides several standard functional interfaces within the java.util.function package to cover common scenarios.^[600-developer__java__java8__java8-lambda.md]
- Consumer\
: Represents an operation that accepts a single input argument and returns no result (unary function from T to void).^[600-developer__java__java8__java8-lambda.md] - Function\
: Represents a function that accepts one argument and produces a result (unary function from T to R).^[600-developer__java__java8__java8-lambda.md] - Predicate\
: Represents a predicate (boolean-valued function) of one argument (unary function from T to boolean).^[600-developer__java__java8__java8-lambda.md] - Supplier\
: Represents a supplier of results, taking no arguments but returning a value (nilary function to R).^[600-developer__java__java8__java8-lambda.md]
Usage Example¶
The Function\<T, R> interface can be used to pass logic into a method.^[600-developer__java__java8__java8-lambda.md] The interface defines the relationship between the parameter type T and the return type R (Interface Function<參數,返回值>).^[600-developer__java__java8__java8-lambda.md]
In the following example, javaLamdba accepts an integer and a function defining what operation to perform on it:
// Definition accepting an Integer and a Function mapping Integer to Integer
public Integer javaLamdba(Integer a, java.util.Function<Integer, Integer> fun) {
return fun.apply(a);
}
// Usage with different Lambda expressions defining the action
Integer result1 = javaLamdba(2, param -> param * param); // Square
Integer result2 = javaLamdba(2, param -> param + param); // Add
Integer result3 = javaLamdba(2, param -> param / param); // Divide
Related Concepts¶
- [[Lambda Expression]]
- [[Method Reference]]
- [[Stream API]]
Sources¶
- 600-developer__java__java8__java8-lambda.md