JDK8特性-Lombda表达式
1、Lombda介绍
JDK8中的一个重要特性
有时可以简化匿名内部类的实现
这种表达式只针对有一个抽象方法的接口实现(函数式接口:@FunctionalInterface),以简洁的表达式形式实现接口功能来作为方法参数
2、Lombda表达式组成
参数列表:
- 可省略数据类型,后续主体会自动匹配
- 参数间,用英文逗号隔开
- (参数1, 参数2, …)
- 只有一个参数时,括号可省略
->符号:
{表达式主体}:
- 本质就是接口中抽象方法的具体实现
- 只有一个主体语句时,大括号也可省略
3、参考实例
实例一
package com.my.demo;
public class demo04 {
public static void main(String[] args) {
String name="小花";
//animalShout();
//定义匿名内部类作为参数传递给animalShout()方法
animalShout(new Animal(){
public void shout(){
System.out.println(name+"喵喵");
}
});
//使用Lombda表达式作为参数传递给animalShout()方法
animalShout(
()-> System.out.println("Lombda表达式输出:"+name+"喵喵")
);
}
//定义静态方法animalShout,接收“接口类型参数”
public static void animalShout(Animal an){
an.shout();
}
}
//定义动物接口
interface Animal{
public void shout();
}
实例二
package com.my.lombda;
public class Test01 {
public static void main(String[] args) {
animalShout(()->{
System.out.println("无参,无返回值的函数式接口调用!");
});
showSum((x,y)->x+y,10,20);
}
private static void animalShout(Animal animal){
animal.shout();
}
public static void showSum(Calculate calculate,int a,int b){
System.out.println(calculate.sum(a, b));
}
}
//定义无参、无返回值的函数式接口
@FunctionalInterface
interface Animal{
public void shout();
}
//定义有参,有返回值的函数值接口
interface Calculate{
int sum(int a,int b);
}