java8新特性-方法引用
阿新 • • 發佈:2017-12-22
show acc 函數式 類名 抽象方法 bip pub 構造 --
方法引用:若 Lambda 體中的功能,已經有方法提供了實現,可以使用方法引用
(可以將方法引用理解為 Lambda 表達式的另外一種表現形式)
1. 對象的引用 :: 實例方法名
2. 類名 :: 靜態方法名
3. 類名 :: 實例方法名
註意:
①方法引用所引用的方法的參數列表與返回值類型,需要與函數式接口中抽象方法的參數列表和返回值類型保持一致!
②若Lambda 的參數列表的第一個參數,是實例方法的調用者,第二個參數(或無參)是實例方法的參數時,格式: ClassName::MethodName
二、構造器引用 :構造器的參數列表,需要與函數式接口中參數列表保持一致!1. 類名 :: new
三、數組引用
類型[] :: new;
數組引用
/** * 數組引用 */ @Test public void test01() { Function<Integer, String[]> function = (a) -> new String[a]; String[] strings = function.apply(9); System.out.println(strings.length); System.out.println("等同於"); Function<Integer, String[]> function1 = String[]::new; String[] strings1 = function1.apply(9); System.out.println(strings1.length); }
對象的引用 :: 實例方法名
/** * 對象的引用 :: 實例方法名 */ @Test public void test02() { PrintStream ps= System.out; Consumer<String> consumer = (a) -> ps.println(a); consumer.accept("aaaaaaa"); System.out.println("等同於"); Consumer<String> consumer1 = ps::println; consumer1.accept("ghhasdfh"); }
對象的引用 :: 實例方法名
/** * 對象的引用 :: 實例方法名 */ @Test public void test03() { Employee emp = new Employee(101, "張三", 18, 9999.99); Supplier<String> sup = () -> emp.getName(); System.out.println(sup.get()); System.out.println("----------------------------------"); Supplier<String> sup2 = emp::getName; System.out.println(sup2.get()); }
類名 :: 靜態方法名
//類名 :: 靜態方法名 @Test public void test4() { Comparator<Integer> com = (x, y) -> Integer.compare(x, y); System.out.println("-------------------------------------"); Comparator<Integer> com2 = Integer::compare; }
類名 :: 實例方法名
//類名 :: 實例方法名 @Test public void test5() { BiPredicate<String, String> bp = (x, y) -> x.equals(y); System.out.println(bp.test("abcde", "abcde")); System.out.println("-----------------------------------------"); BiPredicate<String, String> bp2 = String::equals; System.out.println(bp2.test("abc", "abc")); System.out.println("-----------------------------------------"); Function<Employee, String> fun = (e) -> e.show(); System.out.println(fun.apply(new Employee())); System.out.println("-----------------------------------------"); Function<Employee, String> fun2 = Employee::show; System.out.println(fun2.apply(new Employee())); }
構造器引用
public void test7(){ Function<String, Employee> fun = Employee::new; BiFunction<String, Integer, Employee> fun2 = Employee::new; }
java8新特性-方法引用