方法引用
若 Lambda 体中的内容有方法已经实现了,我们可以使用方法引用
(可以理解为方法引用是 Lambda 表达式的另一种表现形式)
主要三种语法格式
对象::实例方法名
注意:需要函数式接口方法的入参和返回值 == 引用的对象方法的入参和返回值
@Testpublic void test1(){Consumer<String> consumer1 = s -> System.out.println(s);// 优化 对象::实例方法名// 1:这个是多写了一行,防止直接看不懂,下面才是简化的PrintStream out = System.out;Consumer<String> consumer2 =out::println;// 简化Consumer<String> consumer3 = System.out::println;consumer1.accept("hello world");consumer2.accept("hello world");consumer3.accept("hello world");}
新建类
package com.dance.java8.entity;import lombok.Data;@Datapublic class Person {private String name;private Integer age;}
@Test
public void test3(){
Person person = new Person();
person.setName("flower");
Supplier<String> supplier = person::getName;
System.out.println(supplier.get());
}
类::静态方法名
注意:需要函数式接口方法的入参和返回值 == 引用的对象方法的入参和返回值
@Test
public void test2(){
Comparator<Integer> comparator = Integer::compare;
}
类::实例方法名
注意:需要两个参数,左边参数作为调用者,右边参数作为入参,才可以使用类::实例方法名
@Test
public void test4(){
BiPredicate<String,String> biPredicate1 = (x,y) -> x.equals(y);
// 优化 类::实例方法名
BiPredicate<String,String> biPredicate2 = String::equals;
}
构造器引用
注意:需要调用的构造器的参数列表与函数式接口中的抽象方法列表保持一致
@Test
public void test5(){
Supplier<Person> supplier1 = () -> new Person();
// 构造器引用优化
Supplier<Person> supplier2 = Person::new;
}
