1.为什么使用Lambda表达式
简化匿名内部类的调用
2.Lambda表达式优缺点
优点:简化代码,使代码逼格更高
缺点:不利于debug,可读性较低
3.Lambda表达式规范
·在接口中只能有一个抽象方法
·@FunctionalInterface 标记该接口为函数式接口
·可以通过default修饰为普通方法
·可以定义object类中的方法
注意:Lambda 规定接口中只能有一个需要被实现的方法,不是规定接口中只能有一个方法
@FunctionalInterface
public interface LambdaInterface {
void use();
default String getStr(){
return "str";
}
}
jdk 8 中有另一个新特性:default, 被 default 修饰的方法会有默认实现,不是必须被实现的方法,所以不影响 Lambda 表达式的使用。
语法形式为 () -> {},其中 () 用来描述参数列表,{} 用来描述方法体,-> 为 lambda运算符 ,读作(goes to)。
public class Test {
public static void main(String[] args) {
//普通写法
//new LambdaInterface(){
// @Override
// public void use() {
// System.out.println("use");
// }
//}.use();
//Lambda写法
((LambdaInterface) () -> System.out.println("use")).use();
}
}
4.Lambda使用案例
I. 调用无参函数
@FunctionalInterface
public interface LambdaInterface {
void use();
}
public class Test {
public static void main(String[] args) {
((LambdaInterface)()-> System.out.println("use")).use();
}
}
II.调用有参函数
@FunctionalInterface
public interface LambdaInterface {
void add(int a , int b);
}
public class Test {
public static void main(String[] args) {
((LambdaInterface)(a,b)->System.out.println(a+b)).add(1,2);
}
}
III.精简写法
public class Test {
public static void main(String[] args) {
LambdaInterface lambdaInterface = (a,b) -> {
return a + b;
};
Integer add = lambdaInterface.add(1, 2);
System.out.println(add);
}
}
public class Test {
public static void main(String[] args) {
Integer add = ((LambdaInterface) (a,b) -> a + b).add(1,2);
System.out.println(add);
}
}
IV.集合遍历
public class Test {
public static void main(String[] args) {
List<String> strList = new ArrayList<>();
strList.add("a");
strList.add("b");
strList.add("c");
strList.add("d");
strList.forEach(t -> System.out.println(t));
}
}
V.集合排序
public class Test {
public static void main(String[] args) {
List<Integer> intList = new ArrayList<>();
intList.add(2);
intList.add(4);
intList.add(6);
intList.add(8);
intList.sort((o1, o2) -> o1-o2);
intList.forEach(t -> System.out.println(t));
}
}
VI.线程调用
public class Test {
public static void main(String[] args) {
new Thread(() -> System.out.println()).start();
}
}