一、方法引用:
若 Lambda 体中的功能,已经有方法提供了实现,可以使用方法引用
(可以将方法引用理解为 Lambda 表达式的另外一种表现形式)
1.对象的引用 :: 实例方法名
@Test
public void test01(){
Student st=new Student("里斯", 12, "男");
Supplier<Integer> su=()->st.getAge();
System.out.println(su.get());
Student stu=new Student("里斯", 18, "男");
Supplier<Integer> su1=stu::getAge;
System.out.println(su1.get());
}
2. 类名 :: 静态方法名
@Test
public void test02(){
BiFunction<Integer, Integer, Integer> bi=(x,y)->Integer.compare(x, y);
Integer apply = bi.apply(3, 4);
System.out.println(apply);
BiFunction<Integer, Integer, Integer> bif=Integer::compare;
Integer applyf = bif.apply(3, 4);
System.out.println(applyf);
}
3. 类名 :: 实例方法名
@Test
public void test03(){
BiPredicate< String, String> bi=(x,y)->x.equals(y);
System.out.println(bi.test("w","W"));
BiPredicate< String, String> bip=String::equals;
System.out.println(bip.test("w","W"));
}
注意:
①方法引用所引用的方法的参数列表与返回值类型,需要与函数式接口中抽象方法的参数列表和返回值类型保持一致!
②若Lambda 的参数列表的第一个参数,是实例方法的调用者,第二个参数(或无参)是实例方法的参数时,格式: ClassName::MethodName
二、构造器引用
构造器的参数列表,需要与函数式接口中参数列表保持一致!
类名 :: new
@Test
public void test04(){
//无参构造器
Supplier<Student> s=()->new Student();
System.out.println(s.get());
Supplier<Student> s1=Student::new;
System.out.println(s1.get());
//有参构造器
Function<String, Student> sf=(x)->new Student(x);
System.out.println(sf.apply("name"));
Function<String, Student> sffl=Student::new;
System.out.println(sffl.apply("name"));
}
注意:构造器引用的时候需要在对象中有建立对应的构造器.