1.Lambda表达式基本写法
(int a,int b) -> a + b;
//明确指出参数类型
(int a,int b) -> { int c = a + b; return c; }
//代码多于一行不能省略{} 以及最后一行的return
Lambda1 lambda = (a,b) -> a + b;
interface Lambda1 {
int op(int a, int b);
}
//可以根据上下文推断出参数类型时,可以省略参数类型
a -> a;
//只有一个参数时可以省略(),加了类型声明的情况下不行
2.方法引用
方法引用 | Lambda表达式 | 特点 |
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(); | 类型::new |
3.函数对象的类型
参数个数类型相同且返回值类型相同,用一个函数式接口封装,函数式接口仅包含一个抽象方法,用@Functionallnterface 来检查。
一般写法示例:
public class LambdaDemo1 {
public static void main(String[] args) {
Type1 lambda1 = (int a) -> (a & 1) == 0;
Type1 lambda2 = a -> BigInteger.valueOf(a).isProbablePrime(100);
}
@FunctionalInterface
interface Type1{
boolean op(int a);
}
}
引入泛型写法示例:
public class LambdaDemo2 {
public static void main(String[] args) {
Type2 lambda1 = Student::new;
Type2 lambda2 = ArrayList<Student>::new;
}
@FunctionalInterface
interface Type2<T>{
T op();
}
}