2023.2.4
Lambda表达式
- Lambda表达式说JDK8中一个重要的新特性,它使用一个清晰简洁德表达式来表达一个接口,同时Lambda表达式也简化了对集合以及数组数据的遍历、过滤和提取等操作
//程序一
package oop.demo11_lambda;
public interface Animal {
public abstract void eat();
}
//程序二
package oop.demo11_lambda;
/*
Lambda表达式:
1.使用前提:必须是接口,接口中只能有一个抽象方法
2.使用格式: (数据类型 参数名1,数据类型 参数名2,...)->{方法体}
():代表的是要执行接口中对应的那个抽象方法。如果方法中有参数,那么就需要传递参数
->:固定格式。作用是将小括号中的参数传递给后面大括号方法体中
{}:代表的是实现接口中那个抽象方法的方法体
*/
public class Demo01 {
public static void main(String[] args) {
//匿名内部类的实现方式
useAnimal(new Animal() {
@Override
public void eat() {
System.out.println("狗吃肉");
}
});
//Lambda表达式的实现方式
useAnimal(()->{ //这里的()代表的是eat()方法,eat()方法中小括号里没有写参数,所以Lambda表达式中也不用写
System.out.println("狗吃肉"); //后面的大括号相当于重写了eat()方法
});
}
public static void useAnimal(Animal a){
a.eat();
}
}
/*
Lambda 表达式的简单例子:
// 1. 不需要参数,返回值为 5
() -> 5
// 2. 接收一个参数(数字类型),返回其2倍的值
x -> 2 * x
// 3. 接受2个参数(数字),并返回他们的差值
(x, y) -> x – y
// 4. 接收2个int型整数,返回他们的和
(int x, int y) -> x + y
// 5. 接受一个 string 对象,并在控制台打印,不返回任何值(看起来像是返回void)
(String s) -> System.out.print(s)
*/
//程序一
package oop.demo11_lambda;
public interface Animal {
public abstract void eat();
}
//程序二
package oop.demo11_lambda;
public class Demo01 {
public static void main(String[] args) {
//匿名内部类的实现方式
useAnimal(new Animal() {
@Override
public void eat() {
System.out.println("狗吃肉");
}
});
//Lambda表达式的实现方式
useAnimal(()->{
System.out.println("狗吃肉");
});
}
public static void useAnimal(Animal a){
a.eat();
}
}
函数式接口
//程序一
package oop.demo11_lambda;
@FunctionalInterface //约束接口是一个函数式接口(接口中只能有一个抽象方法)
public interface InterA {
public abstract void print();
}
//程序二
package oop.demo11_lambda;
public class Demo02 {
public static void main(String[] args) {
method(()->{
System.out.println("你好Lambda表达式");
});
}
public static void method(InterA i){
i.print();
}
}
//程序三
package oop.demo11_lambda;
@FunctionalInterface
public interface InterB {
public abstract int getSum(int num1,int num2);
}
//程序四
package oop.demo11_lambda;
public class Demo03 {
public static void main(String[] args) {
method(10,20,(int num1,int num2)->{
return num1 + num2;}); //第三个参数是接口类型,且只有一个抽象方法,因此可以使用Lambda表达式,其相当于重写了抽象方法getSum()
}
public static void method(int num1,int num2,InterB i){
int result = i.getSum(num1, num2);
System.out.println(result);
}
}