方法引用
方法引用:使用操作符 “ : : ” 将方法名和对象或类的名字分隔开来;
如下三种主要使用情况:
对象 : : 实例方法
类 : : 静态方法
类 : : 实例方法
对象 : : 方法名
// 对象实例方法名 @Test public void test1(){ Consumer<String> con = (x) -> System.out.println(x); con.accept("hello"); Consumer<String> con1 = System.out::println; con1.accept("大家好"); }
类 : : 静态方法
//类::静态方法 @Test public void test2(){ Comparator<Integer> comparator = (x,y) -> Integer.compare(x,y); int compare = comparator.compare(1, 2); System.out.println(compare); Comparator<Integer> comparator1 = Integer::compare; int compare1 = comparator1.compare(4,2); System.out.println(compare1); }
类 : : 实例方法名
//类::实例方法名 // 注意:若 Lambda 参数列表中的第一个参数是实例方法的调用者, // 而第二个参数是实例方法的参数时,可以使用 ClassName :: method @Test public void test3(){ BiPredicate<String,String> bp = (x,y) -> x.equals(y); System.out.println(bp.test("xy", "xy")); BiPredicate<String,String> bp2 = String::equals; System.out.println(bp2.test("xy", "xyz")); }
构造器引用
//构造器引用 //注意:需要调用的构造器的参数列表要与函数式接口中抽象方法的参数列表保持一致 @Test public void test4(){ Supplier<Employee> supplier = () -> new Employee(); Employee employee = supplier.get(); System.out.println(employee); //构造器引用方式 ,调用的是无参构造器 Supplier<Employee> supplier1 = Employee::new; Employee employee1 = supplier1.get(); System.out.println(employee1); // 传一个参数 Function<Integer,Employee> function = (x) -> new Employee(x); System.out.println(function.apply(19)); Function<Integer,Employee> function1 = Employee::new; System.out.println(function1.apply(18)); }
数组引用
格式:type[] : : new
//数组引用 @Test public void test5(){ Function<Integer,Integer[]> fun = (x) -> new Integer[x]; Integer[] integers = fun.apply(10); Function<Integer,Integer[]> fun1 = Integer[]::new; Integer[] integers1 = fun1.apply(10); }
原文:https://www.cnblogs.com/lililixuefei/p/13185895.html