JDK8 引用(方法引用、構造器引用、陣列引用)
/**
* @Description:
* 一、方法引用
* 如果lambda 體中的內容有方法已經實現了,我們可以使用“方法引用”
* (可以理解為方法引用是 Lambda表示式的另外一種表現形式)
* 主要有三種語法格式:
* 物件 ::例項方法名
* 類:: 靜態方法名
* 類::例項方法名
* 注 : Lambda 體中呼叫方法的引數列表和返回型別,要與函式式介面中抽象方法的函式列表和返回值型別保持一致!
* 如果lambda 引數列表中的第一引數是例項方法的呼叫者,而第二個引數是例項方法的引數時,可以使用className::method
*
*
*
* 二、構造器引用
* className::new
* 注:需要呼叫的構造器的引數列表要與函式式介面中抽象方法的引數列表引數保持一致
*
* 三、陣列引用
*
* @author:zhangys
* @date:Created in 19:46 2018/12/30
* @Modified By:
*/
public class Demo2 {
/**
* 物件 ::例項方法名
*/
@Test
public void test1(){
Consumer<String> con = (x) -> System.out.println(x);
PrintStream ps = System.out;
Consumer<String> con1 = ps :: println;
con1.accept("ssss");
PrintStream ps1 = System.out;
Consumer<String> con2 = (x) -> ps1.println(x);
}
@Test
public void test2(){
Employee emp = new Employee();
Supplier<String> sup = () -> emp.getName();
String str = sup.get();
System.out.println(str);
Supplier<Integer> sup2 = emp::getAge;
Integer num = sup2.get();
System.out.println(num);
}
/**
* 類:: 靜態方法名
*/
@Test
public void test3(){
Comparator<Integer> com = (x,y) -> Integer.compare(x,y);
Comparator<Integer> com1 = Integer::compareTo;
}
/**
* 類名::例項方法名
*/
@Test
public void test4(){
BiPredicate<String,String> bp = (x,y) -> x.equals(y);
BiPredicate<String,String> bp2 = String::equals;
}
/**
* 構造器引用
*/
@Test
public void test5(){
Supplier<Employee> sup = () -> new Employee();
sup.get();
//構造器引用方式
Supplier<Employee> sup2 = Employee::new;
Employee e = sup2.get();
System.out.println(e);
}
@Test
public void test6(){
Function<Integer,Employee> fun = (x) -> new Employee(x);
Employee e = fun.apply(101);
System.out.println(e);
BiFunction<Integer,Integer,Employee> bf = Employee::new;
}
/**
* 陣列引用
*/
@Test
public void test7(){
Function<Integer,String[]> fun = (x) -> new String[x];
String[] strs = fun.apply(10);
System.out.println(strs.length);
Function<Integer,String[]> fun2 = String[]::new;
String[] strs2 = fun.apply(12);
System.out.println(strs2.length);
}
}