1. 函数引用 :
- 若Lambda体中的内容已经有方法实现过了,则可以使用"方法引用"
- 函数引用可以理解为Lambda表达式的另一种表现形式
2. 语法格式
-
注意 :
- Lambda体中调用方法的参数列表与返回值类型,须与函数式接口中抽象方法的参数列表和返回值类型一直.
- 当Lambda参数列表中,第一个参数是实例函数的调用者,而第二个参数是实例函数的形式参数时,可以是用 类名::实例函数名 的形式.
-
对象名 ::实力函数名
@Test
public void test1() {
// 对象::实例方法名
// 输出任意内容
PrintStream ps = System.out ;
Consumer<String> consumer = (x) ->ps.println(x);
consumer.accept("业精于勤荒于嬉,行成于思毁于随");
PrintStream ps1 = System.out ;
Consumer<String> consumer1 = ps1::println ;
consumer1.accept("马云传:未来的你,一定会感谢今天拼命努力的自己!");
// 函数接口的泛型在控制数据类型
Consumer<Integer> consumer2 = System.out::println;
consumer2.accept(9527);
}
@Test
public void test3() {
// 类名::静态函数
// 编写比较器
Comparator<Integer> comparator = (x, y) -> Integer.compare(x, y);
Comparator<Integer> comparator1 = Integer::compare ;
int compare = comparator1.compare(120, 120);
System.out.println("compare = " + compare);
}
@Test
public void test4() {
// 类名::函数名
// 比较两个字符串
// 方法一 : BiPredicate
BiPredicate<String,String> biPredicate = (x,y)->x.equals(y) ;
System.out.println("biPredicate.test("abc","abc") = " + biPredicate.test("abc", "abc"));
BiPredicate<String,String> biPredicate1 = String :: equals ;
System.out.println(biPredicate1.test("郭靖","郭靖"));
// 方法二 : BiFunction
BiFunction<String,String,Boolean> function = (x, y) -> x.equals(y);
Boolean apply = function.apply("abc", "abc");
System.out.println("apply = " + apply);
BiFunction<String,String,Boolean> function1 = String::equals ;
System.out.println("function1.apply("abc","abc") = " + function1.apply("abc", "abc"));
}
3. 构造器引用
@Test
public void test01() {
// 构造器引用
Employee employee = new Employee();
Supplier<Employee> supplier = Employee::new ;
Employee employee1 = supplier.get();
System.out.println("employee1 = " + employee1);
// 一个参数
Function<String,Employee> function = Employee::new ;
Employee employee2 = function.apply("xiaoixao");
System.out.println("employee2 = " + employee2);
// 二个参数
BiFunction<String,Integer,Employee> biFunction = Employee::new ;
Employee employee3 = biFunction.apply("xiaoxiao", 30);
System.out.println("employee3 = " + employee3);
}
4. 数组引用
@Test
public void test02() {
//
int[] arr = new int[10] ;
Function<Integer,int[]> function = int[]::new ;
int[] ints = function.apply(10);
System.out.println("ints = " + ints);
Function<Integer,Employee[]> function1 = Employee[]::new ;
Employee[] employees = function1.apply(100);
System.out.println(Arrays.toString(employees));
Function<Object[],String> function2 = employees1->Arrays.toString(employees1);
String apply = function2.apply(employees);
System.out.println("apply = " + apply);
}