JAVA8方法引用

方法引用

Lambda有方法已经完成了

1.对象::实例方法名

//案例1:
Consume<String> consume = (x) -> System.out.println(x);

//方法的参数类型和返回值要和要引用的方法的参数类型和返回值一致

PrintStream ps = System.out;
Consumer<String> con1 = ps::println;

//案例2:
Employee emp = new Emplouee();
Supplier<String> sup = () -> emp.getName();
String str = sup.get();
System.out.println(str);

//方法应用实现
Supplier<String> sup = emp::getName();
String name = sup.get();
System.out.println(name);

2.类::静态方法名

Comparator<Integer> com = (x,y) -> Integer.compare(x,y);

//方法的参数类型和返回值要和要引用的方法的参数类型和返回值一致
Comparator<Integer> com = Integer::compare;

3.类::实例方法名

//BiPredicate,传入两个参数返回Boolean

BiPredicate<String,String> bp = (x,y) -> x.equals(y);

BiPredicate<String,String> bp = String::equals;
//若参数列表第一个参数是实例方法的调用者,儿第二个参数是实例方法的参数时,才可以ClassNmae::方法;

构造器引用

注意:

需要调用构造器的参数列表要与函数式接口中的抽象方法的参数列表保持一致!

Supperlier<Employee> sup = () -> new Employee();

Supperlier<Employee> sup = Employee::new;
Employee emp = sup.get();

Function<Integer,Employee> fun = (x) -> new Employee(x);

Function<Integer,Employee> fun = Employee::new;
Employee emp = fun.apply(101);

数组引用

Function<Integer,String[]> fun  = (x) -> new String[x];
String[] strs = fun.apply(10);

Function<Integer,String[]> fun  = String[]::new;
String[] strs = fun.apply(10);
posted @ 2022-06-24 14:32  Arborblog  阅读(39)  评论(0编辑  收藏  举报