只有一种抽象方法的接口称为功能接口。可以添加@FunctionalInterface 批注,以便我们可以将接口标记为功能接口。Java编译器会自动识别功能接口。
lambda表达式主要用于定义功能接口的 内联实现。它消除了对匿名类的需求,并为Java提供了简单而强大的功能编程能力。
几乎没有Java默认接口是下面列出的功能接口
java.lang.Runnable
java.util.concurrent.Callable
java.io.FileFilter
java.util.Comparator
java.beans.PropertyChangeListener
@FunctionalInterface interface interface-name { // only one abstract method }
@FunctionalInterfaceinterface MathOperation { int operation(int a, int b); } public class LambdaExpressionTest { public static void main(String args[]) { MathOperation addition = (a, b) -> a + b; // lambda expression MathOperation multiplication = (int a, int b) -> { return a * b; }; // lambda expression System.out.println("The addition of two numbers are: " + addition.operation(5, 5)); System.out.println("The multiplication of two numbers are: " + multiplication.operation(5, 5)); } }
输出结果
The addition of two numbers are: 10 The multiplication of two numbers are:: 25