java8中的方法引用
来源:互联网 发布:oracle误删除数据恢复 编辑:程序博客网 时间:2024/05/21 22:21
public class Java8test {public static void main(String[] args) {List<Apple> ls = ImmutableList.of(new Apple("1","绿色",20),new Apple("2","绿色",30),new Apple("3", "黄色",40)).asList();List<Apple> l = three(ls, Java8test::isYellowApple);for (Apple apple : l) {System.out.println(apple.getId());}}public static List<Apple> three(List<Apple> ls,Predicate<Apple> p) {List<Apple> l = new ArrayList<>();for (Apple apple : ls) {if(p.test(apple)){l.add(apple);}}return l;}public static boolean isYellowApple(Apple a) {return "黄色".equals(a.getColor());}public static boolean isGreaterThanTwenty(Apple a) {return a.getWeigt()>20;}}
ImmutableList是guava包中的一个类。
上述代码可以看到,我们将单个的比较条件抽离出来,作为单独的方法,并通过方法引用的方式,将我们的方法作为参数传入。
方法引用有很多种,我们这里使用的是静态方法引用写法为Class名称::方法名称
其它如:
- 静态方法引用:
ClassName::methodName
- 实例上的实例方法引用:
instanceReference::methodName
- 超类上的实例方法引用:
super::methodName
- 类型上的实例方法引用:
ClassName::methodName
- 构造方法引用:
Class::new
- 数组构造方法引用:
TypeName[]::new
我们也可以替换成lambda的方式
public class Java8test {public static void main(String[] args) {List<Apple> ls = ImmutableList.of(new Apple("1","绿色",20),new Apple("2","绿色",30),new Apple("3", "黄色",40)).asList();List<Apple> l = three(ls, (Apple a) -> "黄色".equals(a.getColor()));for (Apple apple : l) {System.out.println(apple.getId());}}public static List<Apple> three(List<Apple> ls,Predicate<Apple> p) {List<Apple> l = new ArrayList<>();for (Apple apple : ls) {if(p.test(apple)){l.add(apple);}}return l;}public static boolean isYellowApple(Apple a) {return "黄色".equals(a.getColor());}public static boolean isGreaterThanTwenty(Apple a) {return a.getWeigt()>20;}}
当然,用不用lambda方式还是取决于lambda够不够长,如果很长的话,并且不是一眼就能明白它的行为,那么还是应该用方法引用的方式来指向一个有具体描述意义的方法。
阅读全文
1 0
- java8中的方法引用
- Java8 的方法引用
- Java8方法引用(::)
- java8之方法引用
- Java8---5.方法引用
- Java8之方法引用
- java8 方法引用
- Java8 _ 方法引用 ::
- java8-静态方法引用
- Java8 MethodReference方法引用
- java8之方法引用
- Java8之方法引用
- java8 - 方法引用(method referrance)
- java8 - 方法引用(method referrance)
- java8系列之方法引用
- Java8 实战学习 方法引用
- Java8 方法引用-Method References
- Java8新特性--方法引用
- vs code 设置php.validate.executablePath
- iOS开发稀碎小技巧四
- java.class文件结构学习
- mysql 基础知识
- spring boot中的异步执行(@EnableAsync,@Async)
- java8中的方法引用
- xss filter绕过技巧
- javaweb随笔(四)------SpringMVC与Struts2的主要区别
- servletContext 记录
- 开发自测工具
- SpringMVC框架初探(本文是自己学习SpringMVC框架的认识可能理解的不深,不喜勿喷)
- 你是否应该使用规则引擎
- yocto
- 剑指Offer-63