- Lambda是JDK1.8推出的重要新特性。
- Lambda的使用格式:
(1)方法中具有单行语句:
(参数) ->单行语句;
(2)方法中具有多行语句:
(参数) ->{} - 使用Lambda时的要求:
(1)在实现接口时使用;
(2)接口必须只有一个方法,如果有两个方法,则无法使用函数式编程。
(3)如果现在某 个接口就是为了函数式编程而生的,最好在定义时就让其只能够定义一个方法,所以有了一个新的注解:@FunctionalInterface。
(4)如果现在你的表达式里只有一行进行数据的返回,那么直接使用语句即可,可以不使用return。 - Lambda的使用
(1)方法中有单行语句
@FunctionalInterface
interface Person{
public void fun();
}
public class LambdaTest {
public static void main(String[] args) {
//覆写了fun()方法
Person p = () -> System.out.println("这条语句是覆写了fun()方法,是对该方法的填充");
//使用fun()方法
p.fun();
}
}
(2)方法中有多行语句
@FunctionalInterface
interface Person{
public void fun();
}
public class LambdaTest {
public static void main(String[] args) {
//覆写了fun()方法
Person p = () -> {
System.out.println("方法中包含多条语句");
System.out.println("第一条。。。");
System.out.println("第二条。。。");
};
//使用fun()方法
p.fun();
}
}
(3)如果现在你的表达式里只有一行进行数据的返回,那么直接使用语句即可,可以不使用return。
@FunctionalInterface
interface Person{
public int add(int x,int y);
}
public class LambdaTest {
public static void main(String[] args) {
//覆写了fun()方法
Person p = (p1,p2) -> p1+p2;
//使用fun()方法
System.out.println(p.add(2,3));
}
}