Lambda表达式
1.简介
Lambda表达式是JDK1.8开始之后的新技术,是一种代码的新语法。
是一种特殊写法
2.作用
简化匿名内部类的代码写法
3.格式
(匿名内部类被重写方法的形参列表) -> {
被重写方法的方法体代码。
}
-> 就是一个新语法,没有实际含义,但是不能省略!
4.使用前提
Lambda表达式只能简化函数式接口的匿名内部类写法:
函数式接口(FunctionalInterface):
- 必须是接口。
- 接口中只能有一个抽象方法。
5.代码示例1
public class LambdaDemo1 {
public static void main(String[] args) {
/*new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"正在运行...");
}
}).start();*/
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"正在运行...");
}).start();
}
}
6.代码示例2
class Student{
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class LambdaDemo2 {
public static void main(String[] args) {
Student s1 = new Student("a",1);
Student s2 = new Student("b",2);
Student s3 = new Student("c",3);
Student s4 = new Student("c",4);
List<Student> list = new ArrayList<>();
Collections.addAll(list,s1,s2,s3,s4);
/*Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return s1.getAge()-s2.getAge();
}
});*/
Collections.sort(list, (Student o1,Student o2)->{
return s1.getAge()-s2.getAge();
});
System.out.println(list.toString());
}
}
7.Lambda表达式的省略写法
-
如果 Lambda表达式的方法体代码只有一行代码。可以省略大括号不写,同时要省略分号!
new Thread(()->{ //只有1行代码 System.out.println(Thread.currentThread().getName()+"正在运行..."); }).start(); //改成: new Thread(()->System.out.println(Thread.currentThread().getName()+"正在运 行...")).start();
-
如果 Lambda表达式的方法体代码只有一行代码。可以省略大括号不写。此时,如果这行代码是 return语句,必须省略 return不写,同时也必须省略";"不写
Collections.sort(list, (Student o1,Student o2)->{ return s1.getAge()-s2.getAge(); }); //改成 Collections.sort(list, (Student o1,Student o2) -> s1.getAge()-s2.getAge());
-
参数类型可以省略不写。
-
如果只有一个参数,参数类型可以省略,同时()也可以省略。
public class LambdaDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.forEach(new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
});
list.forEach((String s)->{
System.out.println(s);
});
list.forEach((s)->{
System.out.println(s);
});
list.forEach(s->{
System.out.println(s);
});
list.forEach(s->System.out.println(s));
}
}