方法引用:若 Lambda 体中的功能,已经有方法提供了实现,可以使用方法引用
(可以将方法引用理解为 Lambda 表达式的另外一种表现形式)
1. 对象的引用 :: 实例方法名
2. 类名 :: 静态方法名
3. 类名 :: 实例方法名
注意:
①方法引用所引用的方法的参数列表与返回值类型,需要与函数式接口中抽象方法的参数列表和返回值类型保持一致!
②若Lambda 的参数列表的第一个参数,是实例方法的调用者,第二个参数(或无参)是实例方法的参数时,格式: ClassName::MethodName
二、构造器引用 :构造器的参数列表,需要与函数式接口中参数列表保持一致!
1. 类名 :: new
三、数组引用
类型[] :: new;
数组引用
/**
* 数组引用
*/
@Test
public void test01() {
Function<Integer, String[]> function = (a) -> new String[a];
String[] strings = function.apply(9);
System.out.println(strings.length);
System.out.println("等同于");
Function<Integer, String[]> function1 = String[]::new;
String[] strings1 = function1.apply(9);
System.out.println(strings1.length);
}
对象的引用 :: 实例方法名
/**
* 对象的引用 :: 实例方法名
*/
@Test
public void test02() {
PrintStream ps = System.out;
Consumer<String> consumer = (a) -> ps.println(a);
consumer.accept("aaaaaaa");
System.out.println("等同于");
Consumer<String> consumer1 = ps::println;
consumer1.accept("ghhasdfh");
}
对象的引用 :: 实例方法名
/**
* 对象的引用 :: 实例方法名
*/
@Test
public void test03() {
Employee emp = new Employee(101, "张三", 18, 9999.99);

Supplier<String> sup = () -> emp.getName();
System.out.println(sup.get());

System.out.println("----------------------------------");

Supplier<String> sup2 = emp::getName;
System.out.println(sup2.get());

}
类名 :: 静态方法名
//类名 :: 静态方法名
@Test
public void test4() {
Comparator<Integer> com = (x, y) -> Integer.compare(x, y);

System.out.println("-------------------------------------");

Comparator<Integer> com2 = Integer::compare;
}
类名 :: 实例方法名
//类名 :: 实例方法名
@Test
public void test5() {
BiPredicate<String, String> bp = (x, y) -> x.equals(y);
System.out.println(bp.test("abcde", "abcde"));

System.out.println("-----------------------------------------");

BiPredicate<String, String> bp2 = String::equals;
System.out.println(bp2.test("abc", "abc"));

System.out.println("-----------------------------------------");


Function<Employee, String> fun = (e) -> e.show();
System.out.println(fun.apply(new Employee()));

System.out.println("-----------------------------------------");

Function<Employee, String> fun2 = Employee::show;
System.out.println(fun2.apply(new Employee()));

}
构造器引用
public void test7(){
Function<String, Employee> fun = Employee::new;

BiFunction<String, Integer, Employee> fun2 = Employee::new;
}