jdk1.8 lambda變量引用

方法引用

若lambda體中的內容有方法已經實現了,那麼可以使用“方法引用”
也可以理解爲方法引用是lambda表達式的另外一種表現形式並且其語法比lambda表達式更加簡單

(a) 方法引用
三種表現形式:

  1. 對象::實例方法名
  2. 類::靜態方法名
  3. 類::實例方法名 (lambda參數列表中第一個參數是實例方法的調用 者,第二個參數是實例方法的參數時可用)

public void test() {
/**
*注意:
* 1.lambda體中調用方法的參數列表與返回值類型,要與函數式接口中抽象方法的函數列表和返回值類型保持一致!
* 2.若lambda參數列表中的第一個參數是實例方法的調用者,而第二個參數是實例方法的參數時,可以使用ClassName::method
*
*/
Consumer con = (x) -> System.out.println(x);
con.accept(100);

    // 方法引用-對象::實例方法
    Consumer<Integer> con2 = System.out::println;
    con2.accept(200);

    // 方法引用-類名::靜態方法名
    BiFunction<Integer, Integer, Integer> biFun = (x, y) -> Integer.compare(x, y);
    BiFunction<Integer, Integer, Integer> biFun2 = Integer::compare;
    Integer result = biFun2.apply(100, 200);

    // 方法引用-類名::實例方法名
    BiFunction<String, String, Boolean> fun1 = (str1, str2) -> str1.equals(str2);
    BiFunction<String, String, Boolean> fun2 = String::equals;
    Boolean result2 = fun2.apply("hello", "world");
    System.out.println(result2);
}

(b)構造器引用
格式:ClassName::new

public void test2() {

    // 構造方法引用  類名::new
    Supplier<Employee> sup = () -> new Employee();
    System.out.println(sup.get());
    Supplier<Employee> sup2 = Employee::new;
    System.out.println(sup2.get());

    // 構造方法引用 類名::new (帶一個參數)
    Function<Integer, Employee> fun = (x) -> new Employee(x);
    Function<Integer, Employee> fun2 = Employee::new;
    System.out.println(fun2.apply(100));

}

©數組引用

格式:Type[]::new

public void test(){
// 數組引用
Function<Integer, String[]> fun = (x) -> new String[x];
Function<Integer, String[]> fun2 = String[]::new;
String[] strArray = fun2.apply(10);
Arrays.stream(strArray).forEach(System.out::println);
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章