Lambda表达式
明确指出参数类型
(int a, int b) -> a + b;
代码多余一行,不能省略{}以及最后一行的return
(int a, int b) -> {int c = a + b; return c;}
Lambda1 lambda = (a, b) -> a + b;
interface Lambda1{
int op(int a, int b);
}
函数对象-方法引用
Math::max = (int a, int b) -> Math.max(a, b);
Student::getName = (Student stu) -> stu.getName();
System.out::println = (Object obj) -> System.out.println(obj);
Student::new = () -> new Student();
练习
1)判断语法正确性
interface Lambda1 {
int op(int a, int b);
}
interface Lambda2{
void op(Object obj);
}
- Lambda1 lambda = a, b -> a-b 正确 错误,参数多于一个需要用括号,Lambda1 lambda = (a, b) -> a – b;
- Lambda1 lambda = (a, b) -> c * b; 正确 正确
- Lambda1 lambda = (int a, b) -> a + b; 错误 错误
- Lambda2 lambda = Object a -> Systemc.out.println(a); 正确 错误 (Object a) -> Systemc.out.println(a); 或者 a -> System.out.println(a);
- Math:random ()->Math.random();
- Math::sqrt (double number) -> Math.sqrt(number);
- Student::getName; (Student stu) -> stu.getName();
- Student::setName; (Studnet stu, String newName) -> stu.setName(newName);
- Student::hashCode; (Student stu) -> stu.hashCode();
- Student::equals; (Sutdnet stu, Object o) -> stu.equals(o);
假设已有对象 Student stu = new Student(“张三”);
- stu::getName