java8中的方法引用

xiaoxiao2021-02-28  60

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 可参考http://www.cnblogs.com/figure9/archive/2014/10/24/4048421.html

我们也可以替换成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够不够长,如果很长的话,并且不是一眼就能明白它的行为,那么还是应该用方法引用的方式来指向一个有具体描述意义的方法。

转载请注明原文地址: https://www.6miu.com/read-67223.html

最新回复(0)