一、方法引用:
若 Lambda 體中的功能,已經有方法提供瞭實現,可以使用方法引用
(可以將方法引用理解為 Lambda 表達式的另外一種表現形式)
1.對象的引用: 實例方法名
@Test public void test01(){ Student st=new Student("裡斯", 12, "男"); Supplier su=()->st.getAge(); System.out.println(su.get()); Student stu=new Student("裡斯", 18, "男"); Supplier su1=stu::getAge; System.out.println(su1.get()); }
2. 類名 :: 靜態方法名
@Test public void test02(){ BiFunction bi=(x,y)->Integer.compare(x, y); Integer apply = bi.apply(3, 4); System.out.println(apply); BiFunction 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 s=()->new Student(); System.out.println(s.get()); Supplier s1=Student::new; System.out.println(s1.get()); //有參構造器 Function sf=(x)->new Student(x); System.out.println(sf.apply("name")); Function sffl=Student::new; System.out.println(sffl.apply("name")); }
註意:構造器引用的時候需要在對象中有建立對應的構造器.