package com.expgiga.Java8;
import java.io.PrintStream;
import java.util.Comparator;
import java.util.function.*;
/**
* 一、方法引用:若Lambda体中的内容有方法已经实现了,可以使用"方法引用"(可以理解为方法引用是Lambda表达式的另外一种表现形式)
*
* 主要有三种语法格式:
*
* 对象::实例方法名
*
* 类::静态方法名
*
* 类::实例方法名
*
* 注意:
* ①Lambda体中调用方法的参数列表与返回值类型,要与函数式接口中抽象方法的函数列表和返回值类型保持一致。
* ②Lambda参数列表中的第一个参数是实例方法的调用者,第二个参数是实例方法的参数时,可以使用ClassName::method
*
* 二、构造器引用:
* 格式:
* ClassName::new
*
* 注意:
* 需要调用的构造器的参数列表要与函数式接口中抽象方法的参数列表保持一致。
*
* 三、数组引用
* Type::new;
*/
public class TestMethodRef {
public static void main(String[] args) {
//1.对象::实例方法名
Consumer<String> con = (x) -> System.
out.println(x);
PrintStream ps = System.
out;
Consumer<String> con1 = ps::println;
Consumer<String> con2 = System.
out::println;
con2.accept(
"dfefedfe");
Employee emp =
new Employee();
Supplier<String> sup = () ->
emp.getName();
System.
out.println(sup.get());
Supplier<Integer> sup2 = emp::getAge;
System.
out.println(sup2.get());
//2.类::静态方法名
Comparator<Integer> com = (x, y) -> Integer.
compare(x, y);
Comparator<Integer> com1 = Integer::
compare;
//3.类::实例方法名
BiPredicate<String, String> bp = (x, y) -> x.equals(y);
BiPredicate<String, String> bp2 = String::equals;
//构造器引用
Supplier<Employee> sup3 = () ->
new Employee();
sup3.get();
Supplier<Employee> sup4 = Employee::
new;
Employee employee = sup4.get();
System.
out.println(employee);
Function<Integer, Employee> fun = (x) ->
new Employee(x);
Function<Integer, Employee> fun2 = Employee::
new;
System.
out.println(fun2.apply(
18));
BiFunction<Integer, Integer, Employee> bf = Employee::
new;
//数组引用
Function<Integer, String[]> fun3 = (x) ->
new String[x];
String[] strs = fun3.apply(
10);
System.
out.println(strs.
length);
Function<Integer, String[]> fun4 = String[]::
new;
String[] strs2 = fun4.apply(
20);
System.
out.println(strs2);
}
}