Functional interface
Description
A functional interface is an interface with one method and used as the type of a lambda expression.
public interface ActionListener extends EventListener {
public void actionPerformed(ActionEvent event);
}
ActionListener
has only one method, actionPerformed
.
It is a functional interface.
It doesn't matter what the single method is called,
the Java compiler will match it up to your lambda expression
as long as it has a compatible method signature.
A lambda expression represents an instance of a functional interface.
The type of a lambda expression is a functional interface type.
(String str) -> str.length()
takes a
String parameter and returns its length.
Its type can be any functional interface type with an abstract method that takes a String as a parameter and returns an int.
The following is an example of such a functional interface:
@FunctionalInterface
interface Processor {
int getStringLength(String str);
}
We can assign lambda expression to its functional interface instance.
Processor stringProcessor = (String str) -> str.length();
Example
In the following code we assign a lambda expression to its functional interface. Then we execute the lambda expression by calling the method defined in the functional interface and pass in a parameter.
public class Main {
public static void main(String[] argv) {
Processor stringProcessor = (String str) -> str.length();
String name = "Java Lambda";
int length = stringProcessor.getStringLength(name);
System.out.println(length);/*from ww w . j a v a 2 s.c o m*/
}
}
@FunctionalInterface
interface Processor {
int getStringLength(String str);
}
The code above generates the following result.
Note
A lambda expression by itself cannot be used as a standalone expression.
The type of a lambda expression is inferred by the compiler.