JAVA8方法引用

方法引用

Lambda有方法已经完成了

1.对象::实例方法名

java
//案例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.类::静态方法名

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

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

3.类::实例方法名

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

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

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

构造器引用

注意:

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

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

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

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

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

数组引用

java
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 @   Arborblog  阅读(44)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示