Lambda表达式基本上表示功能接口实例(具有单一抽象方法的接口称为功能接口。示例为java.lang.Runnable)。
Java中的功能接口
功能接口是仅包含一个抽象方法的接口。他们只能展示一种功能。从Java 8开始,lamada表达式可用于表示功能接口的实例。功能接口可以具有许多默认方法。Runnable,ActionListener和Comparable是功能接口的一些示例。 在Java 8之前,我们必须创建匿名内部类对象或实现这些接口。
// Java program to demonstrate functional interface
class Test
{
public static void main(String args[])
{
// create anonymous inner class object
new Thread(new Runnable()
{
@Override
public void run()
{
System.out.println("New thread created");
}
}).start();
}
}
Output:
New thread created
从Java 8开始,我们可以将lamada表达式分配给其功能接口对象,如下所示:
// Java program to demonstrate Implementation of
// functional interface using lambda expressions
class Test
{
public static void main(String args[])
{
// lambda expression to create the object
new Thread(()->
{System.out.println("New thread created");}).start();
}
}
@FunctionalInterface注解
@FunctionalInterface注解用于确保功能接口不能有多个抽象方法。如果存在多个抽象方法,则编译器会标记“‘Unexpected @FunctionalInterface annotation’消息。但是,使用此注释不是强制性的。
// Java program to demonstrate lamda expressions to implement
// a user defined functional interface.
@FunctionalInterface
interface Square
{
int calculate(int x);
}
class Test
{
public static void main(String args[])
{
int a = 5;
// lambda expression to define the calculate method
Squa