版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011890101/article/details/77768199
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够不够长,如果很长的话,并且不是一眼就能明白它的行为,那么还是应该用方法引用的方式来指向一个有具体描述意义的方法。