1.1
Lambda省去面向对象的条条框框,格式由3个部分组成:
-
一些参数
-
一个箭头
-
一段代码
省略规则
在Lambda标准格式的基础上,使用省略写法的规则为:
-
小括号内参数的类型可以省略;
-
如果小括号内有且仅有一个参,则小括号可以省略;
-
如果大括号内有且仅有一个语句,则无论是否有返回值,都可以省略大括号、return关键字及语句分号。
public int compare(Person o1, Person o2) {
return o1.getAge() - o2.getAge();
}
Arrays.sort(arr, ( o1, o2) ->o1.getAge() - o2.getAge()
public class Demo03Arrays {
public static void main(String[] args) {
Person[] arr = { new Person("A", 20), new Person("D", 16), new Person("B", 28),
new Person("E", 27), };
Arrays.sort(arr, new Comparator<Person>() {
public int compare(Person o1, Person o2) {
return o1.getAge() - o2.getAge();
}
});
// 使用lambda表达式,简化匿名内部类
for (Person person: arr) {
System.out.println(person);
}
}
}
1.4使用lambda表达式
public class Demo03Arrays { public static void main(String[] args) { Demo03Person[] arr = { new Person("A", 20),
new Person("D", 16),
new Person("B", 28), new Person("E", 27), }; // 使用lambda表达式,简化匿名内部类 Arrays.sort(arr, (Person o1, Person o2) -> { return o1.getAge() - o2.getAge(); });
//lambda表达式最终效果
//Arrays.sort(arr, ( o1, o2) ->o1.getAge() - o2.getAge() for (Person person : arr) { System.err.println(person ); } } }