方法引用
當要傳遞給Lambda體的操作,已經有實現的方法,就可以使用方法引用!
實現抽象方法的參數列表,必須與方法引用方法的參數列表保持一致
方法引用使用操作符“::”將方法名和對象或者類的名字分隔開來。
三種使用情況:
- 對象::實例方法
- 類::靜態方法
- 類::實例方法
例如:
(x)->System.out.println(x);
等同於:
System.out::println;
例如:
BinaryOperator<Double> bo=(x,y)->Math.pow(x,y)
等同於:
BinaryOperator<Double> bo=Math::pow;
例如:
compare((x,y)->x.equals(y),“abcdef”,“abcdef”);
等同於
compare(String::equals,“abcdef”,“abcdef”);
注意:當需要引用方法的第一個參數是調用對象,並且第二個參數是需要引用方法的第二個參數(或無參數)時:ClassName::mothodName
構造器引用
格式:ClassName::new
與函數式接口相結合,自動與函數式接口中方法兼容。
可以把構造器引用賦值給定義的方法,與構造器參數列表要與接口中抽象方法的參數列表一直
例如:
Function<Integer,MyClass> fun=(n)->new MyClass(n);
等同於:
Function<Integer,MyClass> fun=MyClass::new;
數組引用
格式:type[]::new
例如:
Function<Integer,Integer[]> fun=(n)->new Integer[n];
等同於:
Function<Integer,Integer[]> fun=Integer[]::new;