一、Lambda表达式
目录
(3)构造方法引用: 类名::new (参数)->new 类名(参数)
Lambda表达式:特殊的匿名内部类,语法更简洁
Lambda表达式允许把函数作为一个方法的参数(函数作为方法参数传递),将代码像数据一样传递
(2)语法
<函数式接口><变量名>=(参数1,参数2)->{
//方法体
};
注意: 函数式接口:接口中只有一个抽象方法。
(参数1,参数2): 抽象方法的参数
: 分隔符
{}:表示抽象方法的实现
public static void main(String[] args) {
//匿名内部类
My my=new My() {
@Override
public void eat() {
System.out.println("猜猜我是谁");
}
};
fun(my);
fun(()->{
System.out.println("使用lambda表达式");
});
}
public static void fun(My m){
m.eat();
}
}
//函数式接口
interface My{
public void eat();
}
分析代码:
Thread 类需要 Runnable 接口作为参数,其中的抽象 run 方法是用来指定线程任务内容的核心
为了指定 run 的方法体,不得不需要 Runnable 接口的实现类
为了省去定义一个 Runnable 实现类的麻烦,不得不使用匿名内部类
必须覆盖重写抽象 run 方法,所以方法名称、方法参数、方法返回值不得不再写一遍,且不能写错
而实际上,似乎只有方法体才是关键所在。
//lambda表达式
Runnable task03 = ()-> {
System.out.println("这是使用Lambda表达式完成的");
};
Thread t3=new Thread(task03);
t3.start();
二、无参无返回值
//无参无返回值
public class Test {
public static void main(String[] args) {
fun(()->{
System.out.println("这是lambda表达式");
});
}
public static void fun(Swimm s){
s.swimm();
}
}
//函数式接口
interface Swimm{
public void swimm();
}
三、有参有返回值
当需要对一个对象集合进行排序时, Collections.sort 方法需要一个 Comparator 接口实例来指定排序的规则
//有参有返回值
public class Test02 {
public static void main(String[] args) {
List<Student> list=new ArrayList<>();
list.add(new Student("张三",12,"男") );
list.add(new Student("刘能",45,"男") );
list.add(new Student("广坤",16,"男") );
list.add(new Student("赵四",48,"男") );
Comparator <Student> comparator =( o1,o2)->{
return o1.getAge()- o2.getAge();
};
Collections.sort(list,comparator);
for(Student s: list){
System.out.println(s);
}
}
}
class Student{
private String name;
private int age;
private String sex;
public Student(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
四、详细介绍lambda表达式
五、函数式接口
(1)内置函数式接口的由来
//内置式函数式接口
public class Test03 {
public static void main(String[] args) {
Count a=arr->{
int sum=0;
for(int i:arr){
sum+=i;
}
System.out.println("和:"+sum);
};
fun(a);
}
public static void fun(Count c){
int[] arr={1,56,12,4564,13,14};
c.getSum(arr);
}
}
@FunctionalInterface
interface Count{
public abstract void getSum(int[] arr);
}