java8中的方法引用
阿新 • • 發佈:2018-12-10
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夠不夠長,如果很長的話,並且不是一眼就能明白它的行為,那麼還是應該用方法引用的方式來指向一個有具體描述意義的方法。