本文共 3176 字,大约阅读时间需要 10 分钟。
方法引用,本质上就是Lambda表达式,而Lambda表达式作为函数式接口的实例。所以方法引用,也是函数式接口的实例。
当要传递给Lambda体的操作,已经实现的方法了,可以使用方法引用!
类(或对象) :: 方法名
// 情况一:对象 :: 实例方法
//Consumer中的void accept(T t) //PrintStream中的void println(T t) @Test public void test1() { Consumercom1 = s -> System.out.println(s); com1.accept("朴灿烈"); System.out.println("*******************");// PrintStream ps = System.out;// Consumer con2 = ps::println; Consumer com2 = System.out :: println; com2.accept("张艺兴"); } //Supplier中的T get() //Employee中的String getName() @Test public void test2() { Employee e = new Employee(1001,"朴灿烈",29,100000); //普通方法 Supplier sup1 = new Supplier () { @Override public String get() { return e.getName(); } }; System.out.println(sup1.get()); System.out.println("*********************"); //Lambda表达式 Supplier sup2 = () -> e.getName(); System.out.println(sup2.get()); System.out.println("*********************"); //方法引用 Supplier sup3 = e :: getName; System.out.println(sup3.get()); }
情况二:类 :: 静态方法
//Comparator中的int compare(T t1,T t2) //Integer中的int compare(T t1,T t2) @Test public void test3() { Comparatorcom1 = (o1,o2) -> Integer.compare(o1,o2); System.out.println(com1.compare(12,21)); System.out.println("****************"); Comparator com2 = Integer::compare; System.out.println(com2.compare(12,21)); } //Function中的R apply(T t) //Math中的Long round(Double d) @Test public void test4() { Function fun = new Function () { @Override public Long apply(Double d) { return Math.round(d); } }; System.out.println(fun.apply(2.0)); System.out.println("****************"); Function fun1 = t -> Math.round(t); System.out.println(fun1.apply(2.0)); System.out.println("****************"); Function fun2 = Math :: round; System.out.println(fun2.apply(2.0)); System.out.println("****************"); }
// 情况:类 :: 实例方法
// Comparator中的int comapre(T t1,T t2) // String中的int t1.compareTo(t2) @Test public void test5() { Comparatorcom = (s1,s2) -> s1.compareTo(s2); System.out.println(com.compare("abc","abd")); System.out.println("****************"); Comparator com1 = String :: compareTo; System.out.println(com1.compare("abc","abd")); } //BiPredicate中的boolean test(T t1, T t2); //String中的boolean t1.equals(t2) @Test public void test6() { BiPredicate bip1 = (s1,s2) -> s1.equals(s2); System.out.println(bip1.test("abc", "abc")); System.out.println("**************"); BiPredicate bip2 = String ::equals; System.out.println(bip1.test("abc", "abc")); } // Function中的R apply(T t) // Employee中的String getName(); @Test public void test7() { Employee e = new Employee(1002,"朴灿烈",29,10000); Function fun1 = emp -> emp.getName(); System.out.println(fun1.apply(e)); System.out.println("*************************"); Function fun2 = Employee :: getName; System.out.println(fun2.apply(e)); }
转载地址:http://dtuki.baihongyu.com/