lambda表达式优化了匿名内部类的书写 减少了代码的冗余
函数式接口 定义:
1.在接口中只能有一个抽象方法
2.@FunctionalInterface 标记为函数式接口
3.通过default修饰为普通方法
4.可以定义object的方法
lambda的基础语法:
()--- 参数列表
-> 分隔符
{ } 方法体
例子:
1)无参方法调用
package com.sypm.service;
/**
* Created with IntelliJ IDEA.
*
* @Author: Wang
* @Date: 2024/04/07/22:00
* @Description:
*/
@FunctionalInterface
public interface Example1Interface {
void get();
}
package com.sypm.service;
/**
* Created with IntelliJ IDEA.
*
* @Author: Wang
* @Date: 2024/04/07/22:03
* @Description:
*/
public class Test01 {
public static void main(String[] args) {
//匿名内部类
new Example1Interface() {
@Override
public void get() {
System.out.println("get");
}
}.get();
//lambda表达式
Example1Interface example1Interface = ()->{
System.out.println("使用了lambda表达式的写法");
};
example1Interface.get();
}
}
2)有参方法调用
package com.sypm.service;
/**
* Created with IntelliJ IDEA.
*
* @Author: Wang
* @Date: 2024/04/07/22:15
* @Description:
*/
public interface Example2Interface {
String get(int a,int b);
}
package com.sypm.service;
/**
* Created with IntelliJ IDEA.
*
* @Author: Wang
* @Date: 2024/04/07/22:16
* @Description:
*/
public class Test02 {
public static void main(String[] args) {
//匿名内部类调用
Example2Interface example2Interface = new Example2Interface() {
@Override
public String get(int a, int b) {
return a + "---" + b;
}
};
System.out.println(example2Interface.get(2, 5));
//改为lambda表达式
Example2Interface example2Interface1 = (a,b)->{
return a + "---" + b;
};
System.out.println(example2Interface1.get(3, 4));
}
}
lambda表达式的简化:
package com.sypm.service;
/**
* Created with IntelliJ IDEA.
*
* @Author: Wang
* @Date: 2024/04/07/22:32
* @Description:
*/
public class Test03 {
public static void main(String[] args) {
Example1Interface example1Interface = () -> {
System.out.println("使用了lambda表达式的写法");
};
example1Interface.get();
//简化 基本语法骨架-->加括号包起来-->强转为指定类型-->调用方法
((Example1Interface) () -> {
System.out.println("使用了lambda表达式的写法");
}).get();
}
}
待补充.......................