方法引用以及构造器引用
笔记参考宋红康老师
方法引用
方法引用的使用情景
-
当要传递给Lambda体的操作,已经有实现的方法,可以使用方法引用!
-
方法引用,本质上就是Lambda表示式,而Lambda表达式作为函数式接口的实例,所以方法引用,也就是函数式接口的实例
使用格式
类(或者对象) :: 方法名
具体情况分为如下三种
-
情况1 : 对象 ::非静态方法
-
情况2 : 类::静态方法
-
情况3: 类::非静态方法
//情况一: 对象 :: 实例方法 //Consumer中的 void accept(T t) //PrintStream 中的 void println(T t) @Test public void test1() { Consumer<String> con = t -> System.out.println(t); con.accept("我爱北京"); System.out.println("****************"); PrintStream ps = System.out; Consumer<String> con1 = ps::println; con1.accept("beijing"); } //Supplier 中的 T get() //Employee 中的 String getName() @Test public void test2() { Employee tom = new Employee(1001, "tom", 23, 7890); Supplier<String> sup = () -> tom.getName(); System.out.println(sup.get()); System.out.println("***********************"); Supplier<String> sup1 = tom::getName; System.out.println(sup1.get()); } //情况二: 类 :: 静态方法 //Comparator 中的 int compare(T t1, T t2) //Integer 中的 int compare(T t1,T t2) @Test public void test3() { Comparator<Integer> com1 = (t1, t2) -> t1.compareTo(t2); System.out.println(com1.compare(12, 21)); System.out.println("*************************"); Comparator<Integer> com2 = Integer::compareTo; System.out.println(com2.compare(12, 21)); } //Function中的R apply*(T t) //Math 中的long round(Double d) @Test public void test4() { Function<Double, Long> func1 = d -> Math.round(d); System.out.println(func1.apply(12.3)); System.out.println("************************"); Function<Double, Long> func2 = Math::round; System.out.println(func2.apply(12.6)); } //情况三: 类 :: 实例方法 //Comparator 中的 int compare(T t1,T t2) //String 中的 int t1.compareTo(t2) @Test public void test5() { Comparator<String> com1 = (t1, t2) -> t1.compareTo(t2); System.out.println(com1.compare("adc", "add")); System.out.println("********************"); Comparator<String> com2 = String::compareTo; System.out.println(com2.compare("adc", "adm")); } //BiPredicate中的 boolean test(T t1,T t2); //String 中的 boolean t1.equals(t2) @Test public void test6() { BiPredicate<String, String> bi = ((s, s2) -> s.equals(s2)); System.out.println(bi.test("adb", "adb")); System.out.println("****************************"); BiPredicate<String, String> bi1 = String::equals; System.out.println(bi1.test("adb", "adb")); } //Function 中的 R apply(T t) //Employee 中的 String getName(); @Test public void test7() { Employee jack = new Employee(1001, "JACK", 23, 12000); Function<Employee,String> func = e -> e.getName(); System.out.println(func.apply(jack)); System.out.println("********************"); Function<Employee,String> func1 = Employee::getName; System.out.println(func1.apply(jack));
方法引用使用的要求
-
方法引用使用的要求:要求接口中的抽象方法的形参列表和返回值,与方法引用的方法的参数列表和返回值类型相同!(针对于情况1 和情况2)