Java8新特性 - 方法引用與構造器引用


方法引用

若Lambda體中的內容有方法已經實現了,我們可以使用"方法應用",可以理解為方法引用是Lambda表達式的另外一種表現形式。

使用操作符“::”將方法名和對象或類的名字分隔開

對象 :: 實例方法名

Consumer<String> consumer = (x) -> System.out.println(x);
等同於
Consumer<String> consumer = System.out::println;

類 :: 靜態方法名

BinaryOperator<Double> binaryOperator = (x, y) -> Math.pow(x, y);
等同於
BinaryOperator<Double> binaryOperator = Math::pow;

PS:

  • Lambda體中調用方發的參數列表與返回值類型,必須與函數式接口中抽象方法的參數列表和返回值類型一致

類 :: 實例方法

BiPredicate<String, String> biPredicate = (x, y) -> x.equals(y);
等同於
BiPredicate<String, String> biPredicate = String::equals;

PS:

  • 若Lambda參數列表中的第一個參數是 實例方法的調用者,而第二個參數是實例方法的參數時,可以使用 類 :: 實例方法

構造器引用

格式: ClassName :: new
與函數式接口相結合,自動與函數式接口中方法兼容。

Function<String, Demo> supplier = (x) -> new Demo(x);
等同於
Function<String, Demo> supplier = Demo::new;

實體類方法:

class Demo{
    Integer num;
    String remark;
    public Demo(String remark) {
        this.remark = remark;
    }
    ......
}

PS:需要調用的構造器的參數列表必須與函數式接口中抽象方法的參數列表保持一致。

數組引用

格式: Type :: new

Function<Integer, String[]> function = (x) -> new String[x];
等同於
Function<Integer, String[]> function = String[] :: new;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM