方法引用
1.使用情境:当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用!
2.方法引用,本质上就是Lambda表达式,而Lambda表达式作为函数式接口的实例。所以
方法引用,也是函数式接口的实例。
3. 使用格式: 类(或对象) :: 方法名
4. 具体分为如下的三种情况:
情况1 对象 :: 非静态方法
情况2 类 :: 静态方法
情况3 类 :: 非静态方法
5. 方法引用使用的要求:要求接口中的抽象方法的形参列表和返回值类型与方法引用的方法的
形参列表和返回值类型相同!(针对于情况1和情况2)
情况一:对象 :: 实例方法
Consumer中的void accept(T t)
PrintStream中的void println(T t)
Consumer<String> c1 = str -> System.out.println(str);
c1.accept("北京");
PrintStream ps = System.out;
Consumer<String> c2 = ps::println;
c2.accept("天津");
情况二:类 :: 静态方法
Comparator中的int compare(T t1,T t2)
Integer中的int compare(T t1,T t2)
Comparator<Integer> c1 = (t1, t2) -> Integer.compare(t1, t2);
System.out.println(c1.compare(1, 2));
Comparator<Integer> c2 = Integer::compare;
System.out.println(c2.compare(1, 2));
情况三:类 :: 实例方法 (有难度)
Comparator中的int comapre(T t1,T t2)
String中的int t1.compareTo(t2)
Comparator<String> c1 = (s1, s2) -> s1.compareTo(s2);
System.out.println(c1.compare("a", "c"));
Comparator<String> c2 = String::compareTo;
System.out.println(c2.compare("a", "c"));
构造器引用
和方法引用类似,函数式接口的抽象方法的形参列表和构造器的形参列表一致。
抽象方法的返回值类型即为构造器所属的类的类型
Supplier中的T get()
Employee的空参构造器:Employee();// 自定义对象
Supplier<Employee> s1 = new Supplier<Employee>() {
@Override
public Employee get() {
return new Employee();
}
};
System.out.println(s1.get());
Supplier<Employee> s2 = () -> new Employee();
System.out.println(s2.get());
Supplier<Employee> s3 = Employee::new;
System.out.println(s3.get());
Function中的R apply(T t)
Function<Integer, Employee> f1 = id -> new Employee(id);
System.out.println(f1.apply(11));
Function<Integer, Employee> f2 = Employee::new;
System.out.println(f2.apply(11));
BiFunction中的R apply(T t,U u)
BiFunction<Integer, String, Employee> f1 = (id, name) -> new Employee(id, name);
System.out.println(f1.apply(11, "aa"));
BiFunction<Integer, String, Employee> f2 = Employee::new;
System.out.println(f2.apply(11, "aa"));
数组引用
可以把数组看做是一个特殊的类,则写法与构造器引用一致。
Function中的R apply(T t)
Function<Integer, String[]> f1 = len -> new String[len];
System.out.println(f1.apply(10).length);
Function<Integer, String[]> f2 = String[]::new;
System.out.println(f2.apply(10).length);
本文链接 :https://blog.csdn.net/Platinum_stars/article/details/108283963