Lambda标准格式:
(参数类型 参数名称) -> { 代码语句 }
Person类
public class Person {
private String name;
private int age;
// 省略构造器、toString方法与Getter Setter
}
测试类:
import java.util.Arrays;
import java.util.Comparator;
public class Demo01Comparator {
public static void main(String[] args) {
// 本来年龄乱序的对象数组
Person[] array = {
new Person("古力娜扎", 19),
new Person("迪丽热巴", 18),
new Person("马尔扎哈", 20) };
// 匿名内部类
Comparator<Person> comp = new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o1.getAge() - o2.getAge();
}
};
Arrays.sort(array, comp); // 第二个参数为排序规则,即Comparator接口实例
for (Person person : array) {
System.out.println(person);
}
}
Lambda写法:
import java.util.Arrays;
public class Demo02ComparatorLambda {
public static void main(String[] args) {
Person[] array = {
new Person("古力娜扎", 19),
new Person("迪丽热巴", 18),
new Person("马尔扎哈", 20) };
Arrays.sort(array, (Person a, Person b) -> {
return a.getAge() - b.getAge();
});
for (Person person : array) {
System.out.println(person);
}
}
}
Lambda省略格式:
Arrays.sort(array, (Person a, Person b) -> {
return a.getAge() - b.getAge();
});
||
Arrays.sort(array, (a, b) -> a.getAge() - b.getAge());
1.小括号内参数的类型可以省略;
2.如果小括号内有且仅有一个参,则小括号可以省略;(多个参数 小括号不能省略)
3.如果大括号内有且仅有一个语句(一个分号),则无论是否有返回值,都可以省略大括号、return关键字及语句分号。 (三个要省略必须一起省略)